Quick Sort is a Divide and Conquer algorithm. It picks an element as pivot and partitions the given array around the picked pivot. There are many different versions of quick Sort that pick pivot in different ways.
- Always pick first element as pivot.
- Always pick last element as pivot (implemented below)
- Pick a random element as pivot.
- Pick median as pivot.
Program:
#include <iostream>
using namespace std;
void swap(int arr[],int i,int j)
{
int temp;
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
int partition(int arr[],int l,int r) //function for finding pivot
{
int pivot = arr[r];
int i = l-1;
for(int j = l; j < r; j++)
{
if(arr[j] < pivot)
{
i ++;
swap(arr,i,j);
}
}
swap(arr,i+1,r);
return i+1;
}
void quickSort(int arr[],int l,int r) //function for sorting
{
if(l < r)
{
int pi = partition(arr,l,r);
quickSort(arr,l,pi-1);
quickSort(arr,pi+1,r);
}
}
int main()
{
int arr[] = {9,-3,5,2,6,8,-6,1,3};
int n=sizeof(arr) / sizeof(arr[0]);
quickSort(arr,0,n-1);
for(int i = 0; i < n; i ++)
cout << arr[i] << " ";
return 0;
}
Output:
-6 -3 1 2 3 5 6 8 9
C++ Program For Quick Sort
Reviewed by Beast Coder
on
March 03, 2021
Rating:
No comments: