Cod sursa(job #734865)

Utilizator a08iAndrei Ionescu a08i Data 15 aprilie 2012 02:11:48
Problema Sortare prin comparare Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 0.92 kb
#include<vector>
#include<iostream>
#include<ctime>
#include<cstdlib>
#include<cstdio>

using namespace std;

int random(int n)
{
  return rand() % (n+1);
}

int i, j, p;

void quicksort(vector<int> &store, int first, int last)
{

if(first >= last)
{
  return;
}

// pivot
p = first + random(last-first);
swap(store[p], store[first]);

i = first+1;
j = first+1;

while(j<=last)
{
  if(store[j] < store[first])
  {
    swap(store[j], store[i]);
    i++;
  }
  j++;
}
swap(store[i-1], store[first]);

quicksort(store, first, i-2);
quicksort(store, i, last);

}


int main()
{
  freopen("algsort.in", "r", stdin);
  freopen("algsort.out", "w", stdout);

  srand(time(0));

  int N, temp;
  scanf("%d", &N);

  vector<int> store;
  store.reserve(N);

  for(int i=0; i<N; i++)
  {
    scanf("%d", &temp);
    store.push_back(temp);
  }

  quicksort(store, 0, store.size()-1);

  for(int i = 0; i<N; i++)
  {
    printf("%d ", store[i]);
  }

}