Pagini recente » Cod sursa (job #1246445) | Cod sursa (job #958503) | Cod sursa (job #1830869) | Istoria paginii utilizator/horatiuros | Cod sursa (job #1238643)
#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 int GetPoz(const int st, const int dr)
{
int poz1 = st + (rand() % (dr - st + 1));
int poz2 = st + (rand() % (dr - st + 1));
int poz3 = st + (rand() % (dr - st + 1));
if (a[poz1] <= a[poz2] && a[poz1] <= a[poz3])
{
if (a[poz2] <= a[poz3])
return poz2;
return poz3;
}
if (a[poz2] <= a[poz1] && a[poz2] <= a[poz3])
{
if (a[poz1] <= a[poz3])
return poz1;
return poz3;
}
if (a[poz1] <= a[poz2])
return poz1;
return poz2;
}
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 = GetPoz(st, dr);
//int poz = (st+dr)/2;
int pivot = a[poz];
int l = st, r = dr;
while (l <= r)
{
while (a[l] < pivot)
++ l;
while (a[r] > pivot)
-- r;
if (l <= r)
{
swap(a[l], a[r]);
++l, --r;
}
}
QuickSort(st, l-1);
QuickSort(l, 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;
}