Wikipedia has very good explanation about heap sort and why its time complexity is O(nlogn):

*“The heapsort algorithm involves preparing the list by first turning it into a max heap. The algorithm then repeatedly swaps the first value of the list with the last value, decreasing the range of values considered in the heap operation by one, and sifting the new first value into its position in the heap. This repeats until the range of considered values is one value in length.*

*The steps are:*

*Call the buildMaxHeap() function on the list. Also referred to as heapify(), this builds a heap from a list in O(n) operations.*
*Swap the first element of the list with the final element. Decrease the considered range of the list by one.*
*Call the siftDown() function on the list to sift the new first element to its appropriate index in the heap.*
*Go to step (2) unless the considered range of the list is one element.*

*The buildMaxHeap() operation is run once, and is O(n) in performance. The siftDown() function is O(log(n)), and is called n times. Therefore, the performance of this algorithm is O(n + n * log(n)) which evaluates to O(n log n).”*

Some key points to understand this algorithm and its implementation:

- the heap data structure is actually a virtual thought, it exists only in our imagination, in reality, we’re only re-positioning the elements into different indices, this is also why heap sort space complexity is O(1), since it doesn’t require any extra memory
- how do we construct this virtual heap data structure? some keys to understand it:
- regard the array as an
**level order traversal** of a complete binary tree (draw out the picture, and then you’ll have a better understanding)
- how to construct a
**max** heap? we always want the parent’s val to be greater than its both children’s val, so we swap the two if we find a situation that doesn’t follow this rule and recursively do it.
- how do we find a node’s left and right children?
- if you draw out the tree, you’ll figure out that: a node with index
**i**, its left child will be **2*i** and its right child will be **2*i+1**, if the two children exist.

- Heap sort in NOT stable: the relative order of equal elements might be changed since heapsort peeks the largest element and put it at the last of list.

Used the wikipedia example input: 6, 5, 3, 1, 8, 7, 2, 4 to test my code:

public class _20160710_HeapSortAgain {
private static int N;
public static void sort(int[] nums){
heapify(nums);
for(int i = N; i > 0; i--){//i doesn't need to be equal to zero, because we don't need to swap zero-indexed number with itself
swap(nums, i, 0);//we always swap the first element in the array which means it's at the root of the heap with the number at index i which is the largest index in the UN-sorted array
N -= 1;//don't remember to decrement N by 1, because we only need to worry about one number fewer each time
maxheap(nums, 0);//then we always update the heap for the number at index zero
}
}
private static void heapify(int[] nums) {
N = nums.length-1;
for(int i = N/2; i >= 0; i--){//here we need i to be equal to zero because we need to do maxheap() on its first element as well
maxheap(nums, i);
}
}
private static void maxheap(int[] nums, int i) {
int leftChildIndex = 2*i;
int rightChildIndex = leftChildIndex+1;
int max = i;
if(leftChildIndex <= N && nums[leftChildIndex] > nums[i]){
max = leftChildIndex;
}
if(rightChildIndex <= N && nums[rightChildIndex] > nums[max]){
max = rightChildIndex;
}
if(i != max){
swap(nums, i, max);
maxheap(nums, max);
}
}
private static void swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
public static void main(String...strings){
int[] nums = new int[]{6,5,3,1,8,7,2,4};
// int[] nums = new int[]{1,2,3,4,5,6};
// int[] nums = new int[]{6,5,4,3,2,1};
print("BEFORE printing, nums are: ", nums);
sort(nums);
print("AFTER printing, nums are: ", nums);
System.out.println();
}
private static void print(String msg, int[] nums) {
System.out.println(msg);
for(int i : nums){
System.out.print(i + ", ");
}
System.out.println();
}
}