Cod sursa(job #2197748)

Utilizator LivcristiTerebes Liviu Livcristi Data 22 aprilie 2018 20:28:10
Problema Sortare prin comparare Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.1 kb
#include <iostream>
#include <fstream>
#define NUM 500005
int v[NUM];
int n;
void schimb(int &a, int &b)
{
    int aux = a;
    a = b;
    b = aux;
}
int partitie(int st, int dr)
{
    int pivot = v[st];
    int i = st - 1, j = dr + 1;

    while (true)
    {
        do
        {
            i++;
        }
        while (v[i] < pivot);
        do
        {
            j--;
        }
        while (v[j] > pivot);
        if (i >= j)
            return j;
        schimb(v[i], v[j]);
    }
}
void quicksort(int st, int dr)
{
    while(st < dr)
    {
        int p = partitie(st, dr);
        if(p - st < dr - p)
        {
            quicksort(st, p - 1);
            st = p + 1;
        }
        else
        {
            quicksort(p + 1, dr);
            dr = p - 1;
        }
    }
}
using namespace std;
int main()
{
    ifstream f("algsort.in");
    ofstream g("algsort.out");
    f >> n;
    for(int i = 0; i < n; ++i)
        f >> v[i];
    quicksort(0, n - 1);
    for(int i = 0; i < n; ++i)
        g << v[i] << " ";
    f.close();
    g.close();
}