Cod sursa(job #2292268)

Utilizator richard26Francu Richard richard26 Data 29 noiembrie 2018 11:46:39
Problema Sortare prin comparare Scor 60
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.87 kb
#include <bits/stdc++.h>
#define N_max 500010
using namespace std;

int heap[N_max];
void minheap(int n)
{
	while(heap[n] < heap[n / 2])
	{
		swap(heap[n], heap[n / 2]);
		n /= 2;
	}
}

void erase(int n)
{
	swap(heap[1], heap[n]);
	int i = 1;
	while((heap[i] > heap[i * 2] && i * 2 < n) || (heap[i] > heap[i * 2 + 1] && i * 2 + 1 < n))
	{
		if (heap[i * 2] < heap[i * 2 + 1] && i * 2 < n)
		{
			swap(heap[i], heap[i * 2]);
			i *= 2;
		}
		else if(heap[i * 2] > heap[i * 2 + 1] && i * 2 + 1 < n)
		{
			swap(heap[i], heap[i * 2 + 1]);
			i = i * 2 + 1;
		}
		 else if (i * 2 < n)
		 {
			swap(heap[i], heap[i * 2]);
		 	i *= 2;
		 }
	}
}

int main()
{
	ifstream f("algsort.in");
	ofstream g("algsort.out");

	int n;
	f>>n;
	for (int i = 1; i <= n; i++)
	{
		int x;
		f>>x;
		heap[i] = x;
		minheap(i);
	}

	for (int i = 0; i < n; i++)
	{
		g<<heap[1]<<" ";
		erase(n - i);

	}

	return 0 ;
}