Cod sursa(job #1795151)

Utilizator DanFodorFODOR Dan Horatiu DanFodor Data 2 noiembrie 2016 00:41:25
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.63 kb
#include <iostream>
#include <fstream>

using namespace std;

void quick_sort(int vect[], int first, int last)
{
    int pivot_index = (first + last)/2;
    int pivot_value = vect[(first + last)/2];
    int i = first, j = last;

    while (i <= j)
    {
        while (vect[i] < pivot_value) ++i;
        while (vect[j] > pivot_value) --j;

        if (i <= j)
        {
            swap(vect[i], vect[j]);
            ++i,--j;
        }
    }
    if (first < pivot_index)
        quick_sort(vect, first, pivot_index);
    if (pivot_index < last)
        quick_sort(vect, pivot_index, last);
}

void quickSort(int arr[], int left, int right) {
      int i = left, j = right;
      int tmp;
      int pivot = arr[(left + right) / 2];

      /* partition */
      while (i <= j) {
            while (arr[i] < pivot)
                  i++;
            while (arr[j] > pivot)
                  j--;
            if (i <= j) {
                  tmp = arr[i];
                  arr[i] = arr[j];
                  arr[j] = tmp;
                  i++;
                  j--;
            }
      };

      /* recursion */
      if (left < j)
            quickSort(arr, left, j);
      if (i < right)
            quickSort(arr, i, right);
}

int main()
{
    ifstream cin("algsort.in");
    ofstream cout("algsort.out");

    int n, index;
    cin >> n;
    int numbers[n];

    for (index = 0; index < n; ++index)
    {
        cin >> numbers[index];
    }

    quickSort(numbers, 0, n-1);
    for (int i = 0; i < n; ++i)
    {
        cout << numbers[i] << ' ';
    }
    cout << "\n";
    return 0;
}