Heap Sort

HEAP SORT

Introduction: Heaps can be used in sorting an array. In max-heaps, maximum element will always be at the root. Heap Sort uses this property of heap to sort the array.


WORKING OF HEAP SORT

Example: In the diagram below,initially there is an unsorted array Arr having 6 elements and then max-heap will be built.



Step 1: 8 is swapped with 5

Step 2: 8 is disconnected from heap as 8 is in correct position now and

Step 3: Max-heap is created and 7 is swapped with 3

Step 4: 7 is disconnected from heap

Step 5: Max heap is created and 5 is swapped with 1

Step 6: 5 is disconnected from heap

Step 7: Max heap is created and 4 is swapped with 3

Step 8: 4 is disconnected from heap

Step 9: Max heap is created and 3 is swapped with 1

Step 10: 3 is disconnected

After all the steps, we will get a sorted array.