Heapsort is nota stable sort algorithm. In order to learn this algorithm, you need to knowsome concepts first.
Actually, theheap is a binary tree, in this tree a parent node has two children nodes. Theparent is greater than or less than the two children. There are twokinds of heaps, the difference between them is the order of the elements. Ifthe root is the maximum element, it could be called big top heap, if theroot is the minimum element, it could be called small top heap.
The idea of thisalgorithm is build a heap base on the array which is needed to be ordered.Ensure each parent is greater than or less than its two children in the heap,such that after a traversing, the root element will be themaximum or minimum one in the whole heap, than swap the root with the lastleaf node. After that, you should adjust the elements of the heapexcept that last leaf node, and then repeat the processwhich is described above. The last heap is neededto be adjusted will only have one element, and then finished the recursion. Atthe end, you will get an ordered heap.
We assume thatthe original array is needed to sort by ascending order. The detail steps areas followed:
1. Build a binary tree base on the initialarray.
2. Adjust the heap to ensure that parentnode is greater than the two children.
3. Swap the root element with the lastnode.
4. Make the heap except that last node as anew heap, and then recursively execute the step 2 and 3.
5. The recursion will be finished if theinput heap has only one element.
6. At last, you will get a sorted order.
The complexity of heapsort is alwaysO(nlgn).
The following is the implement of heapsortby java.
private void maxHeapify(int[] array, int i,int heapSize){
int largestIndex = i;
int leftIndex = 2*i+1;
int rightIndex = 2*i+2;
if(leftIndex < heapSize &&array[leftIndex] > array[largestIndex]){
largestIndex = leftIndex;
}
if(rightIndex < heapSize&& array[rightIndex] > array[largestIndex]){
largestIndex = rightIndex;
}
if(largestIndex != i){
int temp = array[i];
array[i] = array[largestIndex];
array[largestIndex] = temp;
maxHeapify(array,largestIndex,heapSize);
}
}
private void buildMaxHeap(int[] array){
for(int i = array.length/2;i >= 0;i--){
maxHeapify(array,i,array.length);
}
}
public void heapSort(int array[]){
buildMaxHeap(array);
for(int i = array.length-1;i > 0;i--){
int temp = array[0];
array[0] = array[i];
array[i] = temp;
maxHeapify(array,0, i-1);
}
}