Cod sursa(job #2483717)

Utilizator stormy_weatherelena cristina stormy_weather Data 30 octombrie 2019 09:53:19
Problema Sortare prin comparare Scor 60
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.05 kb
#include<iostream>
#include<vector>
#include<fstream>
using namespace std;

void quick_sort(vector<int> &a, int start, int end) {
  int n = end - start;

  if (n <= 1)
    return;

  int pivot = rand() % n + start;

  int x = start, y = end - 1;
  while (x < y) {
    if (x < pivot) {
      if (a[x] <= a[pivot])
        x++;
      else {
        if (y == pivot) {
          swap(a[x], a[pivot]);
          pivot = x;
        } else {
          if (a[y] >= a[pivot])
            y--;
          else
            swap(a[x], a[y]);
        }
      }
    } else if (x == pivot) {
      if (a[y] >= a[pivot])
        y--;
      else {
        swap(a[pivot], a[y]);
        pivot = y;
      }
    }
  }

  quick_sort(a, start, pivot);
  quick_sort(a, pivot + 1, end);

  return;
}

int main() {

  #ifdef INFOARENA
  ifstream cin("algsort.in");
  ofstream cout("algsort.out");
  #endif

  int n; cin >> n;

  vector<int> a(n);
  for (int i = 0; i < n; i++)
    cin >> a[i];

  quick_sort(a, 0, n);

  for (int i = 0; i < n; i++)
    cout << a[i] << " ";
  cout << "\n";

  return 0;
}