Pagini recente » Cod sursa (job #2528388) | Cod sursa (job #1771537) | Cod sursa (job #859907) | Cod sursa (job #891173) | Cod sursa (job #2547937)
#include<fstream>
#define MAX_N 500000
using namespace std;
int h[MAX_N + 1], heapSize;
void readArray() {
ifstream fin("algsort.in");
fin >> heapSize;
for(int i = 1; i <= heapSize; i++)
fin >> h[i];
fin.close();
}
void Swap(int i, int j) {
int aux = h[i];
h[i] = h[j];
h[j] = aux;
}
void heapDown(int i) {
int l, r, minim;
l = 2 * i;
r = 2 * i + 1;
if(l <= heapSize && h[l] < h[i])
minim = l;
else minim = i;
if(r <= heapSize && h[r] < h[minim])
minim = r;
if(minim != i) {
Swap(i, minim);
heapDown(minim);
}
}
void buildHeap() {
for(int i = heapSize / 2; i >= 1; i--)
heapDown(i);
}
void heapSort() {
ofstream fout("algsort.out");
int i, minim, n;
n = heapSize;
for(i = 1; i <= n; i++) {
minim = h[1];
Swap(1, heapSize);
heapSize--;
heapDown(1);
fout << minim << " ";
}
fout << "\n";
fout.close();
}
int main() {
readArray();
buildHeap();
heapSort();
return 0;
}