目前我有一个在家工作的问题它说,寻找更有效的堆排序?
有可能使堆排序算法更有效率 编写会为了整个列表一次,而不是 将在要素之一的方法一次。
但我想不出到底是什么意思的“而不是增加在时间元素一个”,想必人们必须首先建立一个堆(其中涉及从无序列表逐个添加元素) ,然后一次从堆中删除最大的一个。
这里是我的堆阵列:
import exceptions.exceptions.*;
public class ArrayHeap<T> extends ArrayBinaryTree<T> implements HeapADT<T> {
public ArrayHeap(){
super();
}
public void addElement (T element){
if (count==size())
expandCapacity();
tree[count] = element;
count++;
if (count > 1)
heapifyAdd();
}
private void heapifyAdd(){
int index = count - 1;
while ((index != 0) && (((Comparable)tree[index]).compareTo(tree[(index-1)/2]) < 0))
{
T temp = tree[index];
tree[index] = tree[(index-1)/2];
tree[(index-1)/2] = temp;
index = (index-1)/2;
}
}
public T removeMin(){
if (isEmpty())
throw new EmptyCollectionException ("Empty Heap");
T minElement = findMin();
tree[0] = tree[count-1];
heapifyRemove();
count--;
return minElement;
}
private void heapifyRemove()
{
T temp;
int node = 0;
int left = 1;
int right = 2;
int next;
if ((tree[left] == null) && (tree[right] == null))
next = count;
else if (tree[left] == null)
next = right;
else if (tree[right] == null)
next = left;
else if (((Comparable)tree[left]).compareTo(tree[right]) < 0)
next = left;
else
next = right;
while ((next < count) && (((Comparable)tree[next]).compareTo(tree[node]) < 0)){
temp = tree[node];
tree[node] = tree[next];
tree[next] = temp;
node = next;
left = 2*node + 1;
right = 2*(node+1);
if ((tree[left] == null) && (tree[right] == null))
next = count;
else if (tree[left] == null)
next = right;
else if (tree[right] == null)
next = left;
else if (((Comparable)tree[left]).compareTo(tree[right]) < 0)
next = left;
else
next = right;
}
}
public T findMin() {
if (isEmpty())
throw new EmptyCollectionException ("Empty Heap");
return tree[0];
}
}
这里比较堆排序算法:
import ArrayHeap;
public class HeapSort<T>{
public T[] heapsort(T[] data, int min, int max){
ArrayHeap<T> temp = new ArrayHeap<T>();
for (int c = min; c <= max; c++){
temp.addElement(data[c]);
}
int count = min;
while(!(temp.isEmpty())){
T jj = temp.removeMin();
data[count] = jj;
count ++;
}
return data;
}
我想他们会问你,如果你能找到一个排序算法是递归的,因为最终你会拥有整个订购列表,而不是一次从堆的一个周期(for循环)中删除最大的元素。我会去递归合并排序 – VMMF
@VMMF谢谢,我不知道这个问题是否需要一个完全不同的方法,即使用快速排序或合并排序,或者如果它希望我改进heapsort。无论如何,合并和堆排序的平均复杂度为O(nlogn),那么效率的提高是从哪里来的呢? – creampiedonut
请看这里的'Max-Heapify'和'Build-Max-Heap'函数:https://en.wikipedia.org/wiki/Binary_heap。我认为这就是他们希望你实施的。 –