C++ PROGRAM ON QUICK SORT
QUICK SORT
QuickSort algorithm works on a Divide and Conquer technique. It select an element as pivot and splits the given array around the picked pivot. There are lots of different versions of quickSort that select pivot in different ways.
- Always pick first element as pivot.
- Always pick last element as pivot
- Pick a random element as pivot.
- Pick median as pivot.
The main process in quickSort is partition(). Target of partitions is, given an array and an element x of array as pivot, put x at its correct position in sorted array and put all smaller elements (smaller than x) before x, and put all greater elements (greater than x) after x. All this should be done in linear time.
check this video of Quick-sort with Hungarian folk dance
WRITE A PROGRAM ON QUICK -SORT
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
int partition(int arr[], int p,int r);
void quicksort(int arr[],int p,int r)
{ int q;
if (p<r)
{ q= partition(arr,p,r);
quicksort(arr,p,q-1);
quicksort(arr,q+1,r);
}
int partition(int arr[],int p, int r)
{ int t, k,y,i,x;
x=arr[r];
i=p-1;
for(j=p;j<r;j++)
{ if(arr[j]<=x)
{ i=i+1;
t=arr[i];
arr[i]=arr[j];
arr[j]= t;
}
}
k=arr[i+1];
arr[i+1]=arr[r];
arr[r]=k;
y = i+1;
return y ; }
void main()
{
int arr[8],i;
cout<<“Enter array elements : \n”;
for(i=0;i<8 ;i++)
{ cin>>arr[i]; }
cout<<“\n The array elements are : \n”;
for(i=0;i<8;i++)
{ cout<<arr[i]; }
quicksort(arr,1,8);
cout<<” sorted array elements are :\n”;
for(i=0;i<8;i++)
cout<< arr[i];
getch();
}
OUTPUT :