Quick Sort
Program In C++:-
//Quick Sort
#include<iostream>
using namespace std;
int a[25];
int Partition(int l,int h)
{
int pivot,i,j;
pivot=a[l];
i=l;
j=h;
while(i<j)
{
while(a[i]<=pivot && i<=h)
{
i++;
}
while(a[j]>pivot && j>=l)
{
j--;
}
if(i<j)
{
int x=a[i];
a[i]=a[j];
a[j]=x;
}
}
a[l]=a[j];
a[j]=pivot;
return j;
}
void quicksort(int l,int h)
{
if(l<h)
{
int q=Partition(l,h);
quicksort(l,q-1);
quicksort(q+1,h);
}
}
int main()
{
int i, n;
cout<<"enter size of array"<<endl;
cin>>n;
cout<<"enter elements in array"<<endl;
for(i=0;i<n;i++)
{
cin>>a[i];
}
quicksort(0,n-1);
cout<<"sorted array is:"<<endl;
for(int i=0;i<n;i++)
{
cout<<"\t"<<a[i];
}
}
/* Output:-
enter size of array
5
enter elements in array
12
15
11
10
89
sorted array is:
10 11 12 15 89
Process returned 0 (0x0) execution time : 7.700 s
Press any key to continue. */
//Quick Sort
#include<iostream>
using namespace std;
int a[25];
int Partition(int l,int h)
{
int pivot,i,j;
pivot=a[l];
i=l;
j=h;
while(i<j)
{
while(a[i]<=pivot && i<=h)
{
i++;
}
while(a[j]>pivot && j>=l)
{
j--;
}
if(i<j)
{
int x=a[i];
a[i]=a[j];
a[j]=x;
}
}
a[l]=a[j];
a[j]=pivot;
return j;
}
void quicksort(int l,int h)
{
if(l<h)
{
int q=Partition(l,h);
quicksort(l,q-1);
quicksort(q+1,h);
}
}
int main()
{
int i, n;
cout<<"enter size of array"<<endl;
cin>>n;
cout<<"enter elements in array"<<endl;
for(i=0;i<n;i++)
{
cin>>a[i];
}
quicksort(0,n-1);
cout<<"sorted array is:"<<endl;
for(int i=0;i<n;i++)
{
cout<<"\t"<<a[i];
}
}
/* Output:-
enter size of array
5
enter elements in array
12
15
11
10
89
sorted array is:
10 11 12 15 89
Process returned 0 (0x0) execution time : 7.700 s
Press any key to continue. */
Comments