Pagini recente » Cod sursa (job #2769785) | Cod sursa (job #2778122) | Cod sursa (job #1403178) | Cod sursa (job #532144) | Cod sursa (job #1754393)
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <algorithm>
using namespace std;
#define nmax 500003
/////////////////////////////////////////////////
////////
//////// quicksort Lomuto partition scheme
////////
/////////////////////////////////////////////////
int lpartition(int*A, int lo, int hi)
{
int pivot = A[hi];//alegem pivotul ca fiind elementul din dreapta de tot
int i = lo;//consideram i sfarsitul multimii elementelor <= pivot
for(int j = lo ; j< hi ; j++)//trecem prin toate elementele de la stanga la dreapta
if (A[j] <= pivot)//si cand gasim un element <= pivotul
{
swap(A[i],A[j]);//crestem multimea elementelor <= pivot
i++;
}
swap(A[i],A[hi]);//si la final adaugam la sfarstiul miltimii pe pivot deci o sa avem in stanga toate
//elementele <=pivotul si in dreapta >= pivotul
return i;
}
void lquicksort(int *A, int lo, int hi)//O(n) worst case pt cazul cand sunt aproape sortate
{
if(lo <hi)
{
int p = lpartition(A,lo,hi);
lquicksort(A,lo,p-1);
lquicksort(A,p+1,hi);
}
}
/////////////////////////////////////////////////
////////
//////// quicksort C.A.R Hoare partition scheme optimized
////////
/////////////////////////////////////////////////
int hpartition(int *A, int lo, int hi)
{
int i = lo-1,
j = hi-1,
pivot = A[lo];
while(true)
{
do
{
i = i + 1;
}
while (A[i] < pivot);
do
{
j = j - 1;
}
while (A[j] > pivot);
if(i>=j)
return j;
else
swap(A[i],A[j]);
}
}
void hquicksort(int *A,int lo, int hi)
{
if(lo<hi)
{
int p = hpartition(A,lo,hi);
hquicksort(A,lo,p);
hquicksort(A,p+1,hi);
}
}
//////quicksort hoare imbunatatit
void quicksort(int *A,int lo,int hi)
{
int i = lo,j = hi,pivot = A[lo+(hi-lo)/2];
while(i<j)
{
while(A[i]<pivot)
i++;
while(A[j]>pivot)
j--;
if(i<=j)
{
swap(A[i],A[j]); i++; j--;
}
}
if( i< hi)
quicksort(A,i,hi);
if(j > lo)
quicksort(A,lo,j);
}
ifstream in("algsort.in");
ofstream out("algsort.out");
int main()
{
int n,i;
in >> n;
int heap[n+5];
for( i = 0 ; i < n ; i++)
in >> heap[i];
quicksort(heap,0,n-1);
for(int i = 0 ; i < n ; i ++)
out << heap[i] << " ";
return 0;
}