Pagini recente » Cod sursa (job #556569) | Cod sursa (job #836291) | Cod sursa (job #1616134) | Cod sursa (job #1545502) | Cod sursa (job #3246025)
#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;
}