Cod sursa(job #1333267)

Utilizator atoaderAlexandru Toader atoader Data 2 februarie 2015 22:44:33
Problema Sortare prin comparare Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.25 kb
#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);

	uint32_t 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[i], A[heapSize]);
		heapSize--;
		maxHeapify(heapSize, 1);
	}
}

void sort()
{
	heapSort();
}

int main()
{
	read();
	sort();
	write();
}