Created
January 7, 2017 00:06
-
-
Save anonymous/cb43c9cf965f2fff613e84d566e64eeb to your computer and use it in GitHub Desktop.
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
class GfG{ | |
//1. build heap | |
//2. heap sort | |
//http://www.cs.toronto.edu/~krueger/cscB63h/w07/lectures/tut02.txt | |
void buildHeap(int arr[], int n){ | |
//base case: | |
if(n<1) return; | |
//build heap: do heapify on all non-leaf nodes | |
for (int i = n/2 -1; i >= 0; i--) | |
heapify(arr, n, i); | |
//heap sort: | |
//for getting in-place ascemding order: | |
// - make max heap | |
// - swap max at root with last leaf | |
// - shorten arr and max heap again | |
for(int i=n-1; i>=0; i--){ | |
int tmp = arr[0]; | |
arr[0]=arr[i]; | |
arr[i]=tmp; | |
heapify(arr,i,0); | |
} | |
} | |
//max heap | |
void heapify(int arr[], int n, int i){ | |
int s = i; | |
int l = 2*i + 1; | |
int r = 2*i + 2; | |
//base case: | |
if(l>n-1 && r>n-1) return; | |
if(l<n && arr[l]>arr[s]) s=l; | |
if(r<n && arr[r]>arr[s]) s=r; | |
if(s==i) return; | |
int tmp = arr[i]; | |
arr[i] = arr[s]; | |
arr[s] = tmp; | |
heapify(arr,n,s); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment