(1) Basic idea
Heapsort refers to a sorting algorithm designed using a data structure such as a stacked tree (heap). It is a type of selection sort. It selects data through the heap. It should be noted that if you sort in ascending order, you need to build a large pile, and if you sort in descending order, you need to build a small pile.
(2) Code implementation
Step one: First build a large root heap, starting from the last subtree and adjusting downward.
Step 2: Swap the 0 subscript with the last element, and then continue adjusting downwards
public static void heapSort(int[] array) {
createBigHeap(array);
int end = array.length-1;
while (end > 0) {
swap(array,0,end);
shiftDown(array,0,end);
end--;
}
}
public static void createBigHeap(int[] array) {
for (int parent = (array.length-1-1)/2; parent >= 0; parent--){
shiftDown(array,parent, array.length);
}
}
private static void shiftDown(int[] array,int parent,int len) {
int child = 2*parent +1;
while (child < len){
if (child+1 < len && array[child] < array[child+1]) {
child++;
}
if (array[child] > array[parent]) {
swap(array,child,parent);
parent = child;
child = 2*parent +1;
} else {
break;
}
}
}
(3) Feature summary
1. Heap sort uses a heap to select numbers, which is much more efficient.
2. Time complexity: O(N*logN); Space complexity: O(1)
3. Stability: unstable