每当我在最小堆上进行堆排序时,我得到反向排序的数组。
有没有办法在不使用额外空间的情况下使用堆排序对min heap进行排序?
答案 0 :(得分:0)
使用max-heapify按升序排序,min-heapify按降序排序。
这是堆排序的psudocode。
Heapsort(A) {
BuildHeap(A)
for i <- length(A) downto 2 {
exchange A[1] <-> A[i]
heapsize <- heapsize -1
Heapify(A, 1)
}
BuildHeap(A) {
heapsize <- length(A)
for i <- floor( length/2 ) downto 1
Heapify(A, i)
}
Heapify(A, i) {
le <- left(i)
ri <- right(i)
if (le<=heapsize) and (A[le]>A[i])
largest <- le
else
largest <- i
if (ri<=heapsize) and (A[ri]>A[largest])
largest <- ri
if (largest != i) {
exchange A[i] <-> A[largest]
Heapify(A, largest)
}
}
MaxHeapify的Java实现
MaxHeapify( int[ ] arr, int i )
{
int left = 2 * i + 1;
int right = 2 * i + 2;
int largest = i;
if( left < arr.length && arr[ left ] > arr[ largest ] )
largest = left;
if( right < arr.length && arr[ right ] > arr[ largest ] )
largest = right;
if( largest != i )
{
int temp = arr[ i ];
arr[ i ] = arr[ largest ];
arr[ largest ] = temp;
MaxHeapify( arr, largest );
}
}
Here是算法的动画。