Cod sursa(job #2537900)

Utilizator DavidLDavid Lauran DavidL Data 4 februarie 2020 08:19:22
Problema Sortare prin comparare Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.87 kb
#include <bits/stdc++.h>
using namespace std;
ifstream fi("algsort.in");
ofstream fo("algsort.out");

int n;
int x[500005];

void quick(int st, int dr) {
   if (st >= dr)
      return;

   int pivot = rand() % (dr - st + 1);
   pivot += st;

   for (int i = st; i <= dr; i++) {
      // gasesc mai mare inainte de pivot
      if (x[i] > x[pivot] && i < pivot) {
         swap(x[i], x[pivot]);
         pivot = i;
      }

      // gasesc mai mic dupa pivot
      if (x[i] < x[pivot] && i > pivot) {
         swap(x[i], x[pivot]);
         swap(x[pivot + 1], x[i]);
         pivot++;
      }
   }

   quick(st, pivot - 1);
   quick(pivot + 1, dr);
}

int main()
{
   srand(time(NULL));

   fi >> n;
   for (int i = 1; i <= n; i++)
      fi >> x[i];

   quick(1, n);

   for (int i = 1; i <= n; i++)
      fo << x[i] << " ";

   return 0;
}