Cod sursa(job #1062233)

Utilizator miu_mik93FMI - Paduraru Miruna miu_mik93 Data 20 decembrie 2013 21:32:42
Problema Sortare prin comparare Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.45 kb
#include <iostream>
#include <string>
#include <stdlib.h>
#include <assert.h>
#include <time.h>
#include <algorithm>
#include <vector>
#include <cstdio>
#include <cstring>
#include <fstream>
#include <queue>
#include <cstdlib>
#include <iomanip>
#include <cmath>
#include <stdarg.h>
#include <stdio.h>
#include <set>
using namespace std;
//#include <unordered_map>
#define NMAX 200001
int N, heap[NMAX], a[NMAX];

void urca (int *heap, int poz)
{
	while (poz > 1 && heap[poz] < heap[poz / 2])
	{
		swap (heap[poz], heap[poz / 2]);
		poz /= 2;
	}
}

void coboara (int *heap, int &k, int poz)
{
	if ( poz * 2 > k ) return ;
	int poz_c = poz * 2;
	if ( poz * 2 + 1 <= k && heap[poz * 2 + 1] < heap[poz * 2] )
		poz_c++;
	if ( heap[poz_c] < heap[poz] )
	{
		swap(heap[poz_c], heap[poz]);
		coboara (heap, k, poz_c);
	}
}

void eliminaMin (int *heap, int &k)
{
	heap[1] = heap[k--];
	coboara (heap, k, 1);
}

void insert (int *heap, int&k, int x)
{
	k++;
	heap[k] = x;
	urca (heap, k);
}

void HeapSort (int *heap, FILE *g)
{
	int k = 0;
	for (int i = 0; i < N; i++)
		insert (heap, k, a[i]);
	while ( k > 1 )
	{
		fprintf (g, "%d", heap[1]);
		eliminaMin (heap, k);
	}
}

int main()
{
	FILE *f = fopen ("algsort.in", "r");
	FILE *g = fopen ("algsort.out", "w");

	fscanf (f, "%d", &N);
	for (int i = 0; i < N; i++)
		fscanf (f, "%d", &a[i]);

	HeapSort (heap, g);
	fclose(f);
	fclose(g);
	return 0;
}