Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<bits/stdc++.h>
- using namespace std;
- void heapify(int a[], int n, int i)
- {
- int largest = i;
- int l = 2*i + 1;
- int r = 2*i + 2;
- // If left child is larger than root
- if(l < n && a[l] > a[largest])
- largest = l;
- if(r < n && a[r] > a[largest])
- largest = r;
- if(largest != i)
- {
- swap(a[i], a[largest]);
- heapify(a, n,largest);
- }
- }
- void heapSort(int ar[], int n)
- {
- for(int i = n/2 - 1; i >= 0; i--){
- heapify(ar, n,i);
- }
- for(int i = n - 1; i >= 0; i--){
- swap(ar[0], ar[i]);
- heapify(ar,i,0);
- }
- }
- void print(int a[], int n)
- {
- for(int i = 0 ; i < n; i++){
- cout << a[i] << " ";
- }
- cout << endl;
- }
- int main()
- {
- int ar[] = {12, 11, 13, 5, 6, 7};
- int n = sizeof(ar)/sizeof(ar[0]);
- heapSort(ar,n);
- print(ar,n);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement