Pagini recente » Cod sursa (job #2754478) | Cod sursa (job #2403105) | Borderou de evaluare (job #492024) | Cod sursa (job #2961081) | Cod sursa (job #796342)
Cod sursa(job #796342)
#include <fstream>
#include <iostream>
#include <vector>
#include <cstdlib>
using std::cout;
using std::endl;
using std::fstream;
using std::vector;
typedef unsigned long ulong;
#define MAXN 500001
ulong vec[MAXN];
int ChoosePivot(int start, int end)
{
return start + std::rand()%(end-start);
}
int SwapAroundPivot(ulong vec[], int start, int end, int pivot)
{
while (start <= pivot || pivot <= end)
{
while (start <= pivot && vec[start] <= vec[pivot])
{
start++;
}
if (start <= pivot && vec[start] > vec[pivot])
{
std::swap(vec[start], vec[pivot]);
pivot = start;
start++;
}
while (pivot <= end && vec[pivot] <= vec[end])
{
end--;
}
if (pivot <= end && vec[pivot] > vec[end])
{
std::swap(vec[end], vec[pivot]);
pivot = end;
end--;
}
}
return pivot;
}
void QuickSort(ulong vec[], int start, int end)
{
if (start < end)
{
int pivot = ChoosePivot(start, end);
/*cout << "Start = " << start << endl;
cout << "End = " << end << endl;
cout << "Pivot = " << pivot << endl;*/
pivot = SwapAroundPivot(vec, start, end, pivot);
QuickSort(vec, start, pivot);
QuickSort(vec, pivot+1, end);
}
}
int main()
{
int n;
fstream fin("algsort.in", fstream::in);
fstream fout("algsort.out", fstream::out);
fin >> n;
//cout << n << endl;
for (int i=0; i<n; ++i)
{
fin >> vec[i];
}
fin.close();
QuickSort(vec, 0, n-1);
for (int i=0; i<n; ++i)
{
fout << vec[i] << ' ';
}
//fout << "\n";
fout.close();
return 0;
}