Quicksort

Note: I have used pivot as the middle element each time.

#include <iostream>
using namespace std;
void quicksort(int a[],int left, int right)
{
int i,j,temp,pivot;
i=left;
j=right;
pivot=a[(left+right)/2];
while(i<=j)
{
//For left side
while(a[i]<pivot) i++;
//For right side
while(a[j]>pivot) j--;
// a[i], which is greater than the pivot and a[j], which is less than the pivot, those two are swapping,
// to make the all the elements left of the pivot, smaller than the pivot and right of the pivot, greater than the pivot
if(i<=j)
{
swap(a[i],a[j]);
/* Since after the swap, a[i] is smaller than the pivot & a[j] is greater than the pivot,
so there is no need to start checking from i or j, that's why i++ and j-- is done */
i++;
j--;
}
}
// After this loop, the left side of the present pivot is smaller and the right side is greater.
// Now it's turn to quick sort the left and the right part
if(left<j)
{
quicksort(a,left,j);
}
if(right>i)
{
quicksort(a,i,right);
}
}
int main()
{
int n,l;
cout<<"Enter the size of the array : "<<endl;
cin>>n;
int ar[n];
cout<<"Enter the unsorted array elements : "<<endl;
for(l=0;l<n;l++) cin>>ar[l];
quicksort(ar,0,n-1);
cout<<"The sorted array : "<<endl;
for(l=0;l<n;l++)
{
cout<<ar[l]<<endl;
}
return 0;
}
view raw Quick sort.cpp hosted with ❤ by GitHub

Leave a comment