-
-
Save ox1111/0a9ca0723242ca94dbea1de5428a349e to your computer and use it in GitHub Desktop.
Working of Heap sort
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
static void sort(int arr[]) | |
{ | |
// to sort the elements | |
int n = arr.length; | |
// build max heap | |
for(int i = n/2 - 1 ;i>=0; i--) | |
{ | |
// i=n/2-1 as it will give us the left and right child nodes at the first level of the heap | |
heapify(arr,n,i); | |
} | |
// heap sort | |
// arranges the elements in such order that bigger elements occupy the last places first then followed by smaller elements | |
for(int j = n-1; j>=0; j--) | |
{ | |
// swap the root node from the last element of heap and remove the root node from the heap | |
int temp = arr[0]; | |
arr[0] = arr[j]; | |
arr[j] = temp; | |
// this function will have size 5 instead of 6 and will remove the largest element from the heap to initiate heapsort | |
// this will continue until j = 0 i.e. only one element is left and one element is sorted in itself. | |
// therefore we have the sorted list | |
heapify(arr,j,0); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment