Saturday 15 March 2014

Quick Sort

Quick Sort


#include<conio.h>
#include<iostream.h>
quick(int a[],int beg,int end)
{
int loc,left,right,temp;
left=beg;
right=end;
loc=beg;
step2: while((a[loc]<=a[right])&&(right!=loc))
{
right=right-1;
}
if(loc==right)
{
return loc;
}
if(a[loc]>a[right])
{
temp=a[loc] ;
a[loc]=a[right];
a[right]=temp;
loc=right;
}

while((a[loc]>=a[left])&&(left!=loc))
{
left=left+1;
}
if(loc==left)
{
return loc;
}
if(a[loc]<a[left])
{
temp=a[loc] ;
a[loc]=a[left];
a[left]=temp;
loc=left;
}

goto step2;
}
int main()
{
int a[100],n,l[20],u[20];
int top=-1,beg,end,loc;
cout<<"Enter no. element in the list";
cin>>n;
cout<<"enter element in the list:" ;
for(int i=0;i<n;i++)
{
cin>>a[i];
}
top=top+1 ;
l[top]=0;
u[top]=n-1;
if(n<2)
{
cout<<"list is already sorted";
}
else
{
while(top!=-1)
{
beg=l[top];
end=u[top];
top=top-1;
loc=quick(a,beg,end);
if(loc-1>beg)
{
top=top+1;
l[top]=beg;
u[top]=loc-1;
}
if(loc+1<end)
{
top=top+1;
l[top]=loc+1;
u[top]=end;
}
}
}
cout<<"sorted element are:";
for(i=0;i<n;i++)
{
cout <<a[i];
}
getch();
return 0;
}




No comments:

Post a Comment