Pagini recente » Cod sursa (job #1830097) | Cod sursa (job #1721077) | Cod sursa (job #56939) | Cod sursa (job #2422441) | Cod sursa (job #966156)
Cod sursa(job #966156)
//quicksort with random choice of the pivot
#include<fstream>
#include<cstdlib>
#include<ctime>
using namespace std;
ifstream fin("algsort.in");
ofstream fout("algsort.out");
const int Nmax = 500009;
int N; int K; int A[Nmax];
void Read(){
fin >> N;
for(int i = 1; i <= N; ++i) fin >> A[i];
}
int Partition(int Left, int Right){
int Lt = Left - 1; int Rt = Right + 1; int Pivot = A[Left + rand() % (Right - Left + 1)];
while(1){
do{
++Lt;
}while(A[Lt] < Pivot);
do{
--Rt;
}while(Pivot < A[Rt]);
if(Lt < Rt)
swap(A[Lt], A[Rt]);
else return Lt;
}
return 0;
}
void Quicksort(int Left, int Right){
if(Right == Left) return;
int q = Partition(Left, Right);
if(q < Right)
Quicksort(q , Right);
if(Left < q - 1)
Quicksort(Left, q - 1);
}
void Print(){
for(int i = 1; i <= N; ++i)
fout << A[i] <<" ";
}
int main(){
srand(time(NULL));
Read ();
Quicksort(1, N);
Print();
return 0;
}