稳定性:unstable sort
空间:In-place sort
最优复杂度:O(nlgn)
最差复杂度:O(nlgn)
伪代码:
Max_Heapify(A,i)
{
heapsize = heapsize[A];
largest = i;
if left(i) <= heapsize && A[largest] < A[left(i)]
largest = left(i);
else if right(i) <= heapsize && A[largest] < A[right(i)]
largest = right(i);
if(largest != i)
swap A[i] <-> A[largest];
Max_Heapify(A,largest);
}
build_max_heap(A)
{
for i=floor(n/2) to 1
Max_Heapify(A,i);
}
heapsort(A)
{
build_max_heap(A);
for i=n to 2
swap A[1] <->A[heapsize]
heapsize--;
Max_Heapify(A,1);
}
Java代码:
import java.util.Arrays;
public class Main {
int heapsize;
public static void main(String[] args){
Main m = new Main();
int[] A = {0,1,2,3,5,4,7,9,1,2,5,3,2,1};
m.heapSort(A);
System.out.println(Arrays.toString(A));
//输出:[1, 1, 1, 2, 2, 2, 3, 3, 4, 5, 5, 7, 9]
}
public void maxHeapify(int[] A,int i){
int largest = i;
if(left(i) <= heapsize && A[largest] < A[left(i)])
largest = left(i);
if(right(i) <= heapsize && A[largest] < A[right(i)])
largest = right(i);
if(largest != i){
swap(A,i,largest);
maxHeapify(A,largest);
}
}
public void buildMaxHeap(int[] A){
heapsize = A.length - 1;
for(int i = (A.length-1)/2; i > 0; --i){
maxHeapify(A,i);
}
}
public void heapSort(int[] A){
buildMaxHeap(A);
for(int i = (A.length-1); i > 1; --i){
swap(A,1,heapsize);
heapsize--;
maxHeapify(A,1);
}
}
public int left(int i){
return 2 * i;
}
public int right(int i){
return 2 * i + 1;
}
public void swap(int[] A,int x,int y){
int temp = A[x];
A[x] = A[y];
A[y] = temp;
}
}