Cod sursa(job #3128732)

Utilizator captn333Andreea Capitanu captn333 Data 10 mai 2023 17:25:10
Problema Sortare prin comparare Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.19 kb
#include <iostream>
#include <fstream>

using namespace std;

ifstream fin("algsort.in");
ofstream fout("algsort.out");

int n;
int v[500005];

void Citire();
void Quicksort(int st, int dr);
int Partitionare(int st, int dr);
void Afisare();

int main()
{
    Citire();
    Quicksort(1, n);
    Afisare();

    return 0;
}

void Citire()
{
    fin >> n;
    for(int i = 1; i <= n; i++)
        fin >> v[i];
}

void Quicksort(int st, int dr)
{
    int p;
    if(st < dr)
    {
        p = Partitionare(st, dr);
        Quicksort(st, p - 1);
        Quicksort(p + 1, dr);
    }
}

int Partitionare(int st, int dr)
{
    int pivot = v[st], cnt = 0, pozpivot, i, j;
    for(int i = st + 1; i <= dr; i++)
        if(v[i] <= pivot)
            cnt++;
    pozpivot = st + cnt;
    swap(v[pozpivot], v[st]);
    i = st;
    j = dr;
    while(i <pozpivot && j > pozpivot)
    {
        while(v[i] <= pivot)
            i++;
        while(v[j] > pivot)
            j--;
        if(i < pozpivot && j > pozpivot)
            swap(v[i++], v[j--]);
    }
    return pozpivot;
}

void Afisare()
{
    for(int i = 1; i <= n; i++)
        fout << v[i] << " ";
}