Cod sursa(job #1189414)

Utilizator lvamanuLoredana Vamanu lvamanu Data 22 mai 2014 20:01:53
Problema Sortare prin comparare Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.52 kb
#include <iostream>
#include <stdio.h>

using namespace std; 
#define MAXN 500001
// HeapSort O(nlogn) - worst case and average case

int A[MAXN];

void maxHeapify(int pos, int heapSize) {
    int left = 2 * pos; 
    int right = 2 * pos + 1; 
    int largest; 
    if (left < heapSize && A[left] > A[pos]) {
        largest = left;
    } else {
        largest = pos; 
    }
    if (right < heapSize && A[right] > A[largest]) {
        largest = right; 
    }
    if (largest != pos) {
        swap(A[largest], A[pos]); 
        maxHeapify(largest, heapSize); 
    }
}

void createMaxHeap(int N) { 
    // n /2 elements are the leafs of the heap 
    for (int i = N/2; i >= 0; i--) {
        maxHeapify(i, N); 
    }
}


void heapSort(int N) {
    // 1. Create MAX_Heap of A
    // 2. switch first element from max heap with the last 
    // 3. re max_heapify the elements from 0 to N - 1
    createMaxHeap(N); 
    int heapSize = N; 
    for (int index = N - 1; index >= 2; index --) {
        swap(A[0], A[index]); 
        heapSize -- ;
        maxHeapify(0, heapSize); 
    }
    
}



int main() {
    freopen("algsort.in", "r", stdin); 
    freopen("algsort.out", "w", stdout); 
    int N ; 
    cin >> N; 
    int x; 
    for (int i = 0; i < N; i++) {
        cin >> x; 
        A[i] = x; 
    }
    heapSort(N); 
    for (int i = 0; i < N - 1; i++) {
        cout << A[i] << " "; 
    }
    cout << A[N - 1] << endl; 
    
    fclose(stdin); 
    fclose(stdout); 
    return 0; 
}