Pagini recente » Cod sursa (job #2408109) | Cod sursa (job #2641908) | Cod sursa (job #2202835) | Cod sursa (job #2382526) | Cod sursa (job #1238623)
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <ctime>
using namespace std;
const int NMax = 500010;
int n;
int a[NMax], aux[NMax];
void Read()
{
ifstream f ("algsort.in");
f >> n;
for (int i = 1; i <= n; ++ i)
f >> a[i];
f.close();
}
inline void QuickSort(const int st, const int dr)
{
if (dr - st < 1)
return ;
if (dr - st == 1)
{
if (a[st] > a[dr])
swap(a[st], a[dr]);
return ;
}
int poz = st + (rand() % (dr - st + 1));
//int poz = (st+dr)/2;
int pivot = a[poz];
int l = st, r = dr;
int count = 0;
for (int i = st; i <= dr; ++ i)
{
if (a[i] < pivot)
{
aux[l++] = a[i];
continue;
}
if (a[i] > pivot)
{
aux[r--] = a[i];
continue;
}
}
for (int i = l; i <= r; ++ i)
aux[i] = pivot;
for (int i = st; i <= dr; ++ i)
a[i] = aux[i];
QuickSort(st, l-1);
QuickSort(r+1, dr);
}
void Write()
{
ofstream g ("algsort.out");
for (int i = 1; i <= n; ++ i)
g << a[i] << " ";
g << "\n";
g.close();
}
int main()
{
srand(time(NULL));
Read();
QuickSort(1, n);
Write();
return 0;
}