Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- void create_heap(int *arr, int root, int bottom){
- int child;
- while(root * 2 < bottom){
- if(root * 2 == bottom){
- child = root * 2;
- }
- else if (arr[root * 2] > arr[root * 2 + 1])
- child = root * 2;
- else {
- child = root * 2 + 1;
- }
- if (arr[root] < arr[child]){
- swap(arr[root], arr[child]);
- root = child;
- }
- else return;
- }
- }
- void heap_sort(int *arr, int n){
- for (int i = (n / 2) - 1; i >= 0; i--){
- create_heap(arr, i, n);
- }
- for (int i = n - 1; i >= 1; i--)
- {
- swap(arr[0], arr[i]);
- create_heap(arr, 0, i - 1);
- }
- }
- int main(){
- freopen("sort.in", "r", stdin);
- freopen("sort.out", "w", stdout);
- int n;
- cin>>n;
- int *arr = new int[n];
- for(int i=0; i<n; i++){
- cin>>arr[i];
- }
- heap_sort(arr, n);
- for(int i=0; i<n; i++){
- cout<<arr[i]<<" ";
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement