Cod sursa(job #2197749)

Utilizator LivcristiTerebes Liviu Livcristi Data 22 aprilie 2018 20:30:55
Problema Sortare prin comparare Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.85 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;
}
/* C++ implementation of QuickSort using Hoare's
   partition scheme. */
#include<bits/stdc++.h>
using namespace std;

/* This function takes last element as pivot, places
   the pivot element at its correct position in sorted
    array, and places all smaller (smaller than pivot)
   to left of pivot and all greater elements to right
   of pivot */
int partiti(int arr[], int low, int high)
{
    int pivot = arr[low];
    int i = low - 1, j = high + 1;

    while (true)
    {
        // Find leftmost element greater than
        // or equal to pivot
        do
        {
            i++;
        } while (arr[i] < pivot);

        // Find rightmost element smaller than
        // or equal to pivot
        do
        {
            j--;
        } while (arr[j] > pivot);

        // If two pointers met.
        if (i >= j)
            return j;

        schimb(arr[i], arr[j]);
    }
}

/* The main function that implements QuickSort
 arr[] --> Array to be sorted,
  low  --> Starting index,
  high  --> Ending index */
void quickSort(int arr[], int low, int high)
{
    if (low < high)
    {
        /* pi is partitioning index, arr[p] is now
           at right place */
        int pi = partiti(arr, low, high);

        // Separately sort elements before
        // partition and after partition
        quickSort(arr, low, pi);
        quickSort(arr, pi + 1, high);
    }
}
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(v, 0, n - 1);
    for(int i = 0; i < n; ++i)
        g << v[i] << " ";
    f.close();
    g.close();
}