Cod sursa(job #3246025)

Utilizator MikeStrikeAgache Mihai MikeStrike Data 1 octombrie 2024 15:35:53
Problema Sortare prin comparare Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.74 kb
#include <iostream>
#include <fstream>
#include <vector>


using namespace std;

   void swap(int i, int j, std::vector<int>& array) {
        int temp = array[j];
        array[j] = array[i];
        array[i] = temp;
    }
    
   void siftDown(int currentIdx, int endIdx, std::vector<int>& array) {
        int childOneIdx = currentIdx * 2 + 1;
        while (childOneIdx <= endIdx) {
            int childTwoIdx = (currentIdx * 2 + 2 <= endIdx) ? currentIdx * 2 + 2 : -1;
            int idxToSwap;

            if (childTwoIdx != -1 && array[childTwoIdx] > array[childOneIdx]) {
                idxToSwap = childTwoIdx;
            } else {
                idxToSwap = childOneIdx;
            }

            if (array[idxToSwap] > array[currentIdx]) {
                swap(currentIdx, idxToSwap, array);
                currentIdx = idxToSwap;
                childOneIdx = currentIdx * 2 + 1;
            } else {
                return;
            }
        }
    }
    
  void buildMaxHeap(vector<int>& array) {
        int firstParentIdx = (array.size() - 2) / 2;
        for (int currentIdx = firstParentIdx; currentIdx >= 0; currentIdx--) {
            siftDown(currentIdx, array.size() - 1, array);
        }
    }
    
    
  void heapSort(vector<int>& array) {
        buildMaxHeap(array);
        for (int endIdx = array.size() - 1; endIdx > 0; endIdx--) {
            swap(0, endIdx, array);
            siftDown(0, endIdx - 1, array);
        }
    }

 

int main() {
    ifstream in("algsort.in");
    ofstream out("algsort.out");

    int N;
    in >> N;

    vector<int> array(N);
    for (int i = 0; i < N; i++) {
        in >> array[i]; 
    }

    heapSort(array);

    for (const int& num : array) {
        out << num << " "; 
    }


    return 0;
}