Quick Sort is a Divide-and-conquer Sorting algorithm Because this algorithm first divides a large list into two smaller sub-lists ( low elements and high elements ). Quick Sort can then recursively sort by the sub-lists. Check my Following Link and comment me back if you can do it in other better way.
#include<iostream.h>
#include<conio.h>
int main()
{
int a[10],size,m;
int qsort(int a[],int p,int r);
cout<<"enter array size : ";
cin>>size;
for(m=0;m<size;m++)
{
cout<<"nenter " <<m<<"th element : ";
cin>>a[m];
}
qsort(a,0,size-1);
cout<<endl<<"sorted array is : ";
for(m=0;m<size;m++)
{
cout<<a[m]<<"t";
}
getch();
return 0;
}
int qsort(int a[],int p,int r)
{
int partition(int a[],int x,int y);
int q;
if(p<r)
{
q=partition(a,p,r);
qsort(a,p,q-1);
qsort(a,q+1,r);
}
}
int partition(int a[],int p,int r)
{
int i,x,temp,temp1;
i=p-1;
x=a[r];
int j;
for(j=p;j<=r-1;j++)
{
if(a[j]<=x)
{
i=i+1;
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
temp1=a[r];
a[r]=a[i+1];
a[i+1]=temp1;
return i+1;
}
</pre>
Source Code :
<pre class="brush: cpp">#include<iostream.h>
#include<conio.h>
int main()
{
int a[10],size,m;
int qsort(int a[],int p,int r);
cout<<"enter array size : ";
cin>>size;
for(m=0;m<size;m++)
{
cout<<"nenter " <<m<<"th element : ";
cin>>a[m];
}
qsort(a,0,size-1);
cout<<endl<<"sorted array is : ";
for(m=0;m<size;m++)
{
cout<<a[m]<<"t";
}
getch();
return 0;
}
int qsort(int a[],int p,int r)
{
int partition(int a[],int x,int y);
int q;
if(p<r)
{
q=partition(a,p,r);
qsort(a,p,q-1);
qsort(a,q+1,r);
}
}
int partition(int a[],int p,int r)
{
int i,x,temp,temp1;
i=p-1;
x=a[r];
int j;
for(j=p;j<=r-1;j++)
{
if(a[j]<=x)
{
i=i+1;
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
temp1=a[r];
a[r]=a[i+1];
a[i+1]=temp1;
return i+1;
}
</pre>
No comments:
Post a Comment