C++ Program For Quick Sort

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. 

  1. Always pick first element as pivot.
  2. Always pick last element as pivot (implemented below)
  3. Pick a random element as pivot.
  4. Pick median as pivot.
c++ program for quick sort, quick sorting, sorting, sorting in c++

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 C++ Program For Quick Sort Reviewed by Beast Coder on March 03, 2021 Rating: 5

No comments:

Powered by Blogger.