Pagini recente » Cod sursa (job #370794) | Cod sursa (job #308233) | Cod sursa (job #1341794) | Cod sursa (job #2049052) | Cod sursa (job #1241303)
#include <fstream>
#include <iterator>
#include <vector>
#include <algorithm>
using namespace std;
void heapify(int i, int heap_size, vector<int>& heap) {
int l, r, m;
while (true) {
l = 2*i+1;
r = 2*i+2;
if (l >= heap_size) break;
m = l;
if (r < heap_size && heap[l] < heap[r])
m = r;
if (heap[i] < heap[m]) {
swap(heap[i], heap[m]);
i = m;
}
else
break;
}
}
void sorth(vector<int>& V) {
int i, l, r, m, heap_size = V.size();
while (heap_size > 1) {
swap(V[0], V[--heap_size]);
heapify(0, heap_size, V);
}
}
void makeh(vector<int>& V) {
for (int i = V.size() / 2 - 1; i >= 0; --i) {
heapify(i, V.size(), V);
}
}
int main() {
ifstream fin("algsort.in");
ofstream fout("algsort.out");
int n; fin >> n;
vector<int> V(n);
copy(istream_iterator<int>(fin), istream_iterator<int>(), V.begin());
//make_heap(V.begin(), V.end());
//sort_heap(V.begin(), V.end());
makeh(V);
sorth(V);
copy(V.begin(), V.end(), ostream_iterator<int>(fout, " "));
fout << endl;
return 0;
}