Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- void MaxHeapfy(int Arr[],int last);
- void HeapSort(int Arr[], int last);
- void print(int Arr[], int last);
- int main()
- {
- int i,last;
- cout << "Input Array Size: ";
- cin >> last;
- int Arr[last];
- cout << "Input Array Elements..." <<endl;
- for(i=0;i<last;i++)
- {
- cin >> Arr[i];
- }
- HeapSort(Arr,last);
- print(Arr,last);
- return 0;
- }
- void HeapSort(int Arr[], int last)
- {
- int x=last;
- for(int i=0;i<x-1;i++)
- {
- MaxHeapfy(Arr,last);
- swap(Arr[0],Arr[last-1]);
- last--;
- }
- }
- void MaxHeapfy(int Arr[],int last)
- {
- int parent,child1,child2;
- parent = (last-2)/2;
- for(int i=parent;i>=0;i--)
- {
- child1 = 2*i+1;
- child2 = 2*i+2;
- if(Arr[child1] > Arr[i])
- {
- swap(Arr[child1],Arr[i]);
- }
- if(Arr[child2] > Arr[i] && child2<last)
- {
- swap(Arr[child2],Arr[i]);
- }
- }
- }
- void print(int Arr[],int last)
- {
- for(int i=0;i<last;i++)
- {
- cout << Arr[i] << " ";
- }
- cout <<endl;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement