Skip to content

Instantly share code, notes, and snippets.

@pulkitnehra
Last active June 22, 2020 06:32
Show Gist options
  • Save pulkitnehra/cc0a17c38c58fadd100d969059db94fe to your computer and use it in GitHub Desktop.
Save pulkitnehra/cc0a17c38c58fadd100d969059db94fe to your computer and use it in GitHub Desktop.
Working of Heap sort
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