Heap sort is very easy to implement and its time complexity is O(n log(n)).
Sorting Max-heap:
- Let array S is of size n. where n is no of element to sort
- top=n
- Pop root from heap and put it at S[top]
- top=top-1
- heapify(A,1) //Heapify remaining heap again
- Repeate step 3 to 5 untill heap is empty
Sorting Min-heap:
- Let array S is of size n. where n is no of element to sort
- top=1
- Pop root from heap and put it at S[top]
- top=top+1
- heapify(A,1) //Heapify remaining heap again
- Repeate step 3 to 5 untill heap is empty.
C++ Program for HeapSort
- //HeapSort
- //complexivity O(nlogn)
- #include<iostream>
- #include<new>
- using namespace std;
- void BuildHeap(int *heap,int heapSize);
- void hepify(int *heap,int i,int heapSize);
- void HeapSort(int *heap,int *SortedArray,int &heapSize);
- main(){
- //initialise array of required heap size
- int heapSize;
- cout<<"Enter max element to sort:- "<<endl;
- cin>>heapSize;
- int *heap;
- heap =new int[heapSize+1];
- heap[0]=0;
- //now insert all element in heap
- //after that we hepify it
- cout<<"Enter element of heap :"<<endl;
- //int a;
- for(int i=1;i<=heapSize;i++){
- cin>>heap[i];
- }
- BuildHeap(heap,heapSize); //make it heap
- //Heap Sorting
- int *SortedArray;
- int n;
- n=heapSize;
- SortedArray = new int[heapSize];
- HeapSort(heap,SortedArray,heapSize);
- cout<<" \nSorted Data by Heapsort :"<<endl;
- for(int i=0;i<n;i++){
- cout<<SortedArray[i]<<" ";
- }
- }
- void BuildHeap(int *heap,int heapSize){
- //heapify all node
- for(int i=heapSize/2;i>=1;i--){
- hepify(heap,i,heapSize);
- }
- }
- void hepify(int *heap,int i,int heapSize){
- int left=2*i; //index of left child of ith node
- int right=left+1; //index of right child of ith node
- int largest;
- //find index of largest among (ith node and its left and right child)
- if(left<=heapSize && heap[left]>heap[i])
- largest=left;
- else
- largest=i;
- if(right<=heapSize && heap[right]>heap[largest])
- largest=right;
- //now swap largest with ith node
- if(largest !=i){
- int temp =heap[i];
- heap[i]=heap[largest];
- heap[largest]=temp;
- hepify(heap,largest,heapSize);
- }
- }
- void HeapSort(int *heap,int *SortedArray,int &heapSize){
- //store root node at end of sorted array
- //change value of root node equal to value of last node of heap
- //then remove heap
- //Again apply BuiltHeap & repeat process until all nodes removed
- if(heapSize>=1){
- SortedArray[heapSize-1]=heap[1];
- heap[1]=heap[heapSize];
- heapSize--; // basically removing last node
- hepify(heap,1,heapSize); //again hepify to maintain heap property
- HeapSort(heap,SortedArray,heapSize);
- }
- }
Heap Sort |
Thank you so much for writing keep up like this.
ReplyDelete