Wednesday 4 January 2017

Heap Sort Implementation in Cpp

Heap Sort:-
Heap sort is a comparison based sorting technique based on Binary Heap data structure. It is similar to selection sort where we first find the maximum element and place the maximum element at the end. We repeat the same process for remaining element.

Algorithm:- 
 
Heap Sort Algorithm for sorting in increasing order:
1. Build a max heap from the input data.
2. At this point, the largest item is stored at the root of the heap. Replace it with the last item of the heap followed by reducing the size of heap by 1. Finally, heapify the root of tree.
3. Repeat above steps while size of heap is greater than 1.

 Program:-

#include <bits/stdc++.h>
using namespace std;

void heapify(vector<int>&arr,int n,int i){
    int largest,l,r;
    largest=i;
    l=2*largest+1;
    r=2*largest+2;
    if(l<n && arr[l]>arr[largest]) largest=l;
    if(r<n && arr[r]>arr[largest]) largest=r;
    if(largest!=i){
        swap(arr[largest],arr[i]);
        heapify(arr,n,largest);
    }
}
   
void heapsort(vector<int>&arr,int n){
    for(int i=n/2-1;i>=0;i--){
        heapify(arr,n,i);
    }
    for(int i=n-1;i>0;i--){
        swap(arr[0],arr[i]);
        heapify(arr,i,0);
    }
}

void print(vector<int>&arr){
    for(int i=0;i<arr.size();i++) cout<<arr[i]<<" ";
}
int main()
{
    int n;
    cin>>n;
    vector<int>arr(n);
    for(int i=0;i<n;i++) cin>>arr[i];
    heapsort(arr,n);
    print(arr);
    return 0;
}

No comments:

Post a Comment