Cod sursa(job #2840657)

Utilizator cdenisCovei Denis cdenis Data 28 ianuarie 2022 16:25:11
Problema Sortare prin comparare Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.21 kb
#include <iostream>
#include <fstream>

using namespace std;

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

const int MAX=5e5+5;
int v[MAX],n;

int partition (int arr[], int low, int high)
{
    int pivot = arr[high]; // pivot
    int i = (low - 1); // Index of smaller element and indicates the right position of pivot found so far

    for (int j = low; j <= high - 1; j++)
    {
        // If current element is smaller than the pivot
        if (arr[j] < pivot)
        {
            i++; // increment index of smaller element
            swap(arr[i], arr[j]);
        }
    }
    swap(arr[i + 1], arr[high]);
    return (i + 1);
}

void quickSort(int arr[], int low, int high)
{
    if (low < high)
    {
        /* pi is partitioning index, arr[p] is now
        at right place */
        int pi = partition(arr, low, high);

        // Separately sort elements before
        // partition and after partition
        quickSort(arr, low, pi - 1);
        quickSort(arr, pi + 1, high);
    }
}

int main()
{
    fin >> n;
    for(int i=1;i<=n;i++)
        fin >> v[i];
    quickSort(v,1,n);
    for(int i=1;i<=n;i++)
        fout << v[i] << " ";
    return 0;
}