Pagini recente » Cod sursa (job #110364) | Cod sursa (job #2706288) | Cod sursa (job #3228159) | Cod sursa (job #3271812) | Cod sursa (job #3211923)
#include <fstream>
#include <vector>
using namespace std;
std::ifstream in("algsort.in");
std::ofstream out("algsort.out");
template <typename Type>
class Heap {
private:
// this is a min heap
std::vector<Type> heap;
public:
Heap() : heap{ 0 } {}
void swap(Type& x, Type& y) {
Type z = x;
x = y;
y = z;
}
Type pop() {
Type x = heap[1];
int ind = 1;
int son = 2;
swap(heap[1], heap[heap.size() - 1]);
heap.erase(heap.begin() + heap.size() - 1);
if (son < heap.size()) {
if (son + 1 < heap.size() && heap[son] > heap[son + 1]) {
son++;
}
while (heap[son] < heap[ind]) {
swap(heap[son], heap[ind]);
ind = son;
son = ind * 2;
if (son >= heap.size()) { break; }
if (son + 1 < heap.size() && heap[son] > heap[son + 1]) {
son++;
}
}
}
return x;
}
void add(Type x) {
int ind = heap.size();
heap.push_back(x);
while (heap[ind] < heap[ind / 2] && ind > 1) {
swap(heap[ind], heap[ind / 2]);
ind /= 2;
}
}
};
template <typename Type>
void heapSort(std::vector<Type>& vec) {
Heap<Type> heap;
for (int i = 0; i < vec.size(); i++) {
heap.add(vec[i]);
}
for (int i = 0; i < vec.size(); i++) {
vec[i] = heap.pop();
}
}
int main()
{
std::vector<int> vec;
int n,x;
in >> n;
for (int i = 0; i < n; i++) {
in >> x;
vec.push_back(x);
}
heapSort(vec);
for (int i = 0; i < vec.size(); i++) {
out << vec[i] << " ";
}
}