Pagini recente » Cod sursa (job #3271168) | Cod sursa (job #3260747) | Cod sursa (job #3285463) | Cod sursa (job #474916) | Cod sursa (job #3254727)
///https://infoarena.ro/problema/algsort
///QuickSort
#include <fstream>
#include <cstdlib>
#include <ctime>
#include <algorithm>
#define DIM 500001
using namespace std;
ifstream fin("algsort.in");
ofstream fout("algsort.out");
int n, v[DIM];
int pivot(int st, int dr)
{
int mid=st+(dr-st)/2;
if (v[st] > v[mid])
swap(v[st], v[mid]);
if (v[st] > v[dr])
swap(v[st], v[dr]);
if (v[mid] > v[dr])
swap(v[mid], v[dr]);
int pivotVal = v[mid];
swap(v[mid], v[dr-1]);
int i=st, j=dr-1;
while(true)
{
while (v[++i] < pivotVal);
while (v[--j] > pivotVal);
if (i < j)
swap(v[i], v[j]);
else
break;
}
swap(v[i],v[dr-1]);
return i;
}
void quickSort(int st, int dr) {
if(dr-st<= 10)
{
for(int i=st+1;i<=dr;i++)
{
int temp=v[i];
int j=i-1;
while(j>=st && v[j]>temp)
{
v[j+1]=v[j];
j--;
}
v[j+1]=temp;
}
return;
}
int p=pivot(st,dr);
quickSort(st,p-1);
quickSort(p+1,dr);
}
int main()
{
fin>>n;
for(int i=1;i<=n;i++)
fin>>v[i];
srand(time(0));
quickSort(1,n);
for(int i=1;i<=n;i++)
fout<<v[i]<<" ";
return 0;
}