Pagini recente » Cod sursa (job #3251723) | Cod sursa (job #768361) | Cod sursa (job #2921705) | Cod sursa (job #316046) | Cod sursa (job #796334)
Cod sursa(job #796334)
#include <fstream>
#include <iostream>
#include <vector>
#include <cstdlib>
using std::cout;
using std::endl;
using std::fstream;
using std::vector;
typedef unsigned long ulong;
int ChoosePivot(int start, int end)
{
return start + std::rand()%(end-start);
}
int SwapAroundPivot(vector<ulong>& vec, int start, int end, int pivot)
{
int newPivotPose = pivot;
while (start <= newPivotPose || newPivotPose <= end)
{
while (start <= newPivotPose && vec[start] <= vec[newPivotPose])
{
start++;
}
if (start <= newPivotPose && vec[start] > vec[newPivotPose])
{
std::swap(vec[start], vec[newPivotPose]);
newPivotPose = start;
}
while (newPivotPose <= end && vec[newPivotPose] <= vec[end])
{
end--;
}
if (newPivotPose <= end && vec[newPivotPose] > vec[end])
{
std::swap(vec[end], vec[newPivotPose]);
newPivotPose = end;
}
}
return newPivotPose;
}
void QuickSort(vector<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;
vector<ulong> v;
fstream fin("algsort.in", fstream::in);
fstream fout("algsort.out", fstream::out);
fin >> n;
//cout << n << endl;
v.resize(n);
for (int i=0; i<n; ++i)
{
fin >> v[i];
}
QuickSort(v, 0, n-1);
for (int i=0; i<n; ++i)
{
fout << v[i] << " ";
}
//fout << "\n";
fin.close();
fout.close();
return 0;
}