quicksort hoare code example
Example 1: quicksort
#include <iostream>
using namespace std;
void swap(int*,int*);
int partition(int arr[],int start,int end)
{
int pivot=arr[end];
int index=start;
int i=start;
while(i<end)
{
if(arr[i]<pivot)
{
swap(&arr[index],&arr[i]);
index++;
}
i++;
}
swap(&arr[end],&arr[index]);
return index;
}
void quicksort(int arr[],int start,int end)
{
if(start<end)
{
int pindex=partition(arr,start,end);
quicksort(arr,start,pindex-1);
quicksort(arr,pindex+1,end);
}
}
void display(int arr[],int n)
{
for(int i=0;i<n;i++)
{
cout<<arr[i]<<" ";
}
cout<<endl;
}
int main()
{
int n;
cout<<"enter the size of the array:"<<endl;
cin>>n;
int arr[n];
cout<<"enter the elements of the array:"<<endl;
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
cout<<"sorted array is:"<<endl;
quicksort(arr,0,n-1);
display(arr,n);
return 0;
}
void swap(int *a,int*b)
{
int temp=*a;
*a=*b;
*b=temp;
}
Example 2: quicksort
#define QS_TYPE char*
#define QS_COMPARE(a,b) (strcmp((a),(b)))
void QuickSort(QS_TYPE list[], int beg, int end)
{
QS_TYPE piv; QS_TYPE tmp;
int l,r,p;
while (beg<end)
{
l = beg; p = (beg+end)/2; r = end;
piv = list[p];
while (1)
{
while ((l<=r) && (QS_COMPARE(list[l],piv) <= 0)) l++;
while ((l<=r) && (QS_COMPARE(list[r],piv) > 0)) r--;
if (l>r) break;
tmp=list[l]; list[l]=list[r]; list[r]=tmp;
if (p==r) p=l;
l++; r--;
}
list[p]=list[r]; list[r]=piv;
r--;
if ((r-beg)<(end-l))
{
QuickSort(list, beg, r);
beg=l;
}
else
{
QuickSort(list, l, end);
end=r;
}
}
}