Pagini recente » Cod sursa (job #1370814) | Cod sursa (job #244895) | Statistici Balaceanu Madalina (madalina.balaceanu) | Cod sursa (job #1703925) | Cod sursa (job #1333277)
#include <stdint.h>
#include <limits>
#include <fstream>
using namespace std;
const int MAX_ELEMENTS = 500010;
uint32_t A[MAX_ELEMENTS];
int N;
void read()
{
ifstream in("algsort.in");
in >> N;
for (int i = 1; i <= N; i++)
{
in >> A[i];
}
in.close();
}
void write()
{
ofstream out("algsort.out");
for (int i = 1; i <= N; i++)
{
out << A[i] << " ";
}
out.close();
}
int parent(int i){
return i >> 1;
}
int left(int i){
return i << 1;
}
int right(int i){
return (i << 1) + 1;
}
void maxHeapify(int heapSize, int i){
int l = left(i);
int r = right(i);
int largest;
if (l<=heapSize && A[l] > A[i]){
largest = l;
}
else{
largest = i;
}
if (r <= heapSize && A[r] > A[largest]){
largest = r;
}
if (largest != i){
swap(A[i], A[largest]);
maxHeapify(heapSize, largest);
}
}
void buildMaxHeap(int& heapSize){
heapSize = N;
for (int i = N / 2; i >= 1; i--){
maxHeapify(heapSize, i);
}
}
void heapSort(){
int heapSize;
buildMaxHeap(heapSize);
for (int i = 1; i < N; i++){
swap(A[1], A[heapSize]);
heapSize--;
maxHeapify(heapSize, 1);
}
}
void sort()
{
heapSort();
}
int main()
{
read();
sort();
write();
}