Pagini recente » Cod sursa (job #1960559) | Cod sursa (job #2388122) | Cod sursa (job #254275) | Cod sursa (job #2498888) | Cod sursa (job #2487723)
#include<fstream>
#include<iostream>
#define heapSIZE 500000
using namespace std;
class Heap {
private:
int heapSize;
int heap[heapSIZE];
public:
void readArray(string name_fin) {
int i;
ifstream fin(name_fin);
fin >> heapSize;
for(i = 0; i < heapSize; i++)
fin >> heap[i];
fin.close();
}
void heapDown(int i, int hSize) {
int l, r, p;
l = 2 * i + 1;
r = 2 * i + 2;
if(l < hSize && heap[i] > heap[l])
p = l;
else p = i;
if(r < hSize && heap[p] > heap[r])
p = r;
if(p != i) {
swap(heap[i], heap[p]);
heapDown(p, hSize);
}
}
void buildHeap() {
for(int i = heapSize / 2 - 1; i >= 0; i--)
heapDown(i, heapSize);
}
void heapSort(string name_fout) {
ofstream fout(name_fout);
int val, i;
buildHeap();
for(i = heapSize - 1; i >= 0; i--) {
val = heap[0];
swap(heap[0], heap[i]);
heapDown(0, i);
fout << val << " ";
}
fout << "\n";
fout.close();
}
};
int main() {
Heap h;
h.readArray("algsort.in");
h.buildHeap();
h.heapSort("algsort.out");
return 0;
}