Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<iostream>
- #include<cstdlib>
- using namespace std;
- int arraySize;
- int A[100];
- void input();
- void Max_Heapify(int,int);
- void Build_Max_Heap(int);
- void HeapSort(int);
- void output();
- int main()
- {
- input();
- HeapSort(arraySize);
- output();
- return 0;
- }
- void input()
- {
- int i;
- cout<<"How many numbers : ";
- cin>>arraySize;
- for(i=1;i<=arraySize;i++)
- {
- A[i]=rand()%100;
- }
- A[0]=INT_MIN;
- cout<<"Input : "<<endl;
- for(i=1;i<=arraySize;i++)
- {
- cout<<A[i]<<" ";
- }
- cout<<endl;
- }
- void output()
- {
- cout<<"Output : "<<endl;
- int i;
- for(i=1;i<=arraySize;i++)
- {
- cout<<A[i]<<" ";
- }
- cout<<endl;
- }
- void Max_Heapify(int i, int n)
- {
- int l, r, largest = 1;
- l = 2*i;//Left(i);
- r = 2*i+1;//Right(i);
- if((l<= n) && (A[l]> A[i]) )
- {
- largest = l;
- }
- else
- {
- largest = i;
- }
- if((r<=n) && (A[r] > A[largest]))
- {
- largest = r;
- }
- if(largest != i)
- {
- int temp = A[i];
- A[i] = A[largest];
- A[largest] = temp;
- Max_Heapify(largest, n);
- }
- }
- void Build_Max_Heap(int n)
- {
- int i;
- for (i = n/2; i>0; i--)
- {
- Max_Heapify(i, n);
- }
- }
- void HeapSort(int n)
- {
- Build_Max_Heap(n);
- int i;
- for (i = n; i>=2; i-- )
- {
- int temp = A[1];
- A[1] = A[i];
- A[i] = temp;
- Max_Heapify(1, i-1);
- }
- }
Add Comment
Please, Sign In to add comment