QuickSort is a Divide and Conquer algorithm. It picks an element as a pivot and partitions the given array around the pivot. There are many different versions of quickSort that pick the pivot in different ways.
Always pick the first element as a pivot.
Always pick the last element as a pivot.
Pick a random element as a pivot.
Pick the median as the pivot.
Note: Here we will be implementing quick sort by picking the first element as the pivot.
Quick Sort by picking the first element as the Pivot:
The key function in quick sort is a partition. The target of partitions is to put the pivot in its correct position if the array is sorted and the smaller (or equal) to its left and higher elements to its right and do all this in linear time.
Partition Algorithm:
There can be many ways to do partition, the following pseudo-code adopts the method given in the CLRS book.
We start from the leftmost element and keep track of the index of smaller (or equal) elements as i.
While traversing, if we find a smaller (or equal) element, we swap the current element with arr[i].
Otherwise, we ignore the current element.
Pseudo Code for recursive QuickSort function:
// low –> Starting index, high –> Ending index
quickSort(arr[], low, high) { if (low < high) { // pi is partitioning index, arr[pi] is now at right place pi = partition(arr, low, high); quickSort(arr, low, pi – 1); // Before pi quickSort(arr, pi + 1, high); // After pi } }
Pseudo code for partition() function
/* This function takes first element as pivot, places the pivot element at its correct position in sorted array, and places all smaller (smaller than or equal to pivot) to left of pivot and all greater elements to right of pivot */
partition (arr[], low, high) { // first element as pivot pivot = arr[low] k = high for (i = high; i > low; i--) { if (arr[i] > pivot){ swap arr[i] and arr[k]; k--; } } swap arr[k] and arr[low] return k; }
Illustration of partition() :
Consider: arr[] = { 7, 6, 10, 5, 9, 2, 1, 15, 7 }
First Partition: low = 0, high = 8, pivot = arr[low] = 7 Initialize index of right most element k = high = 8.
Traverse from i = high to low:
if arr[i] is greater than pivot:
Swap arr[i] and arr[k].
Decrement k;
At the end swap arr[low] and arr[k].
Now the correct position of pivot is index 5
First partition
Second Partition: low = 0, high = 4, pivot = arr[low] = 2 Similarly initialize k = high = 4;
The correct position of 2 becomes index 1. And the left part is only one element and the right part has {6, 5, 7}.
Partition of the left half
On the other hand partition happens on the segment [6, 8] i.e., the array {10, 9, 15}. Here low = 6, high = 8, pivot = 10 and k = 8.
The correct position of 10 becomes index 7 and the right and left part both has only one element.
Partition of the right half
Third partition: Here partition the segment {6, 5, 7}. The low = 2, high = 4, pivot = 6 and k = 4. If the same process is applied, we get correct position of 6 as index 3 and the left and the right part is having only one element.
Third partition
The total array becomes sorted in this way. Check the below image for the recursion tree
Recursion tree for partitions
Follow the below steps to implement the approach.
Use a recursive function (say quickSort) to initialize the function.
Call the partition function to partition the array and inside the partition function do the following
Take the first element as pivot and initialize and iterator k = high.
Iterate in a for loop from i = high to low+1:
If arr[i] is greater than pivot then swap arr[i] and arr[k] and decrement k.
After the iteration is swap the pivot with arr[k].
Return k-1 as the point of partition.
Now recursively call quickSort for the left half and right half of the partition index.
Implementation of the above approach.
C++
#include<bits/stdc++.h>usingnamespacestd;/*This function takes first element as pivot, the functionplaces the pivot element(first element) on its sortedposition and all the element lesser than pivot will placedleft to it, and all the element greater than pivot placedright to it.*/intpartition(intarr[],intlow,inthigh){// First element as pivotintpivot=arr[low];intk=high;for(inti=high;i>low;i--){if(arr[i]>pivot)swap(arr[i],arr[k--]);}swap(arr[low],arr[k]);// As we got pivot element index is end// now pivot element is at its sorted position// return pivot element index (end)returnk;}/* The main function that implements QuickSortarr[] --> Array to be sorted,low --> Starting index,high --> Ending index */voidquickSort(intarr[],intlow,inthigh){// If low is lesser than highif(low<high){// idx is index of pivot element which is at its// sorted positionintidx=partition(arr,low,high);// Separately sort elements before// partition and after partitionquickSort(arr,low,idx-1);quickSort(arr,idx+1,high);}}/* Function to print an array */voidprintArray(intarr[],intsize){inti;for(i=0;i<size;i++)cout<<arr[i]<<" ";cout<<endl;}// Driver Codeintmain(){intarr[]={7,6,10,5,9,2,1,15,7};intn=sizeof(arr)/sizeof(arr[0]);quickSort(arr,0,n-1);cout<<"Sorted array: \n";printArray(arr,n);return0;}// This Code is contributed by Harsh Raghav
C
#include<stdio.h>voidswap(int*a,int*b){inttemp=*a;*a=*b;*b=temp;}intpartition(intarr[],intlow,inthigh){intpivot=arr[low];// Choosing the pivot elementintstart=low;intend=high;intk=high;// Iterate from the end of the array to the startfor(inti=high;i>low;i--){// If the current element is greater than the pivot,// swap it with the element at index k and decrement kif(arr[i]>pivot)swap(&arr[i],&arr[k--]);}// Swap the pivot element with the element at index kswap(&arr[low],&arr[k]);returnk;// Return the index of the pivot element after partitioning}voidquickSort(intarr[],intlow,inthigh){if(low<high){// Partition the array and get the index of the pivot elementintidx=partition(arr,low,high);// Recursively sort the subarrays before and after the pivot elementquickSort(arr,low,idx-1);quickSort(arr,idx+1,high);}}voidprintArray(intarr[],intsize){for(inti=0;i<size;i++)printf("%d ",arr[i]);printf("\n");}intmain(){intarr[]={7,6,10,5,9,2,1,15,7};intn=sizeof(arr)/sizeof(arr[0]);// Call quickSort to sort the arrayquickSort(arr,0,n-1);printf("Sorted array: \n");printArray(arr,n);return0;}
Java
importjava.util.Arrays;classQuickSort{/* This function takes first element as pivot, the function places the pivot element(first element) on its sorted position and all the element lesser than pivot will placed left to it, and all the element greater than pivot placed right to it.*/intpartition(intarr[],intlow,inthigh){// First element as pivotintpivot=arr[low];intst=low;// st points to the starting of arrayintend=high;// end points to the ending of the arrayintk=high;for(inti=high;i>low;i--){if(arr[i]>pivot)swap(arr,i,k--);}swap(arr,low,k);// As we got pivot element index is end// now pivot element is at its sorted position// return pivot element index (end)returnk;}// Function to swap two elementspublicstaticvoidswap(int[]arr,inti,intj){inttemp=arr[i];arr[i]=arr[j];arr[j]=temp;}/* The main function that implements QuickSort arr[] --> Array to be sorted, low --> Starting index, high --> Ending index */voidquickSort(intarr[],intlow,inthigh){// If low is lesser than highif(low<high){// idx is index of pivot element which is at its// sorted positionintidx=partition(arr,low,high);// Separately sort elements before// partition and after partitionquickSort(arr,low,idx-1);quickSort(arr,idx+1,high);}}/* Function to print an array */voidprintArray(intarr[],intsize){inti;for(i=0;i<size;i++)System.out.print(arr[i]+" ");System.out.println();}// Driver Codepublicstaticvoidmain(Stringargs[]){intarr[]={7,6,10,5,9,2,1,15,7};intn=arr.length;QuickSortob=newQuickSort();ob.quickSort(arr,0,n-1);System.out.println("Sorted array");ob.printArray(arr,n);}}
Python
# This function takes first element as pivot, the function# places the pivot element(first element) on its sorted# position and all the element lesser than pivot will placed# left to it, and all the element greater than pivot placed# right to it.defpartition(array,low,high):# First Element as pivotpivot=array[low]# st points to the starting of arraystart=low+1# end points to the ending of the arrayend=highwhileTrue:# It indicates we have already moved all the elements to their correct side of the pivotwhilestart<=endandarray[end]>=pivot:end=end-1# Opposite processwhilestart<=endandarray[start]<=pivot:start=start+1# Case in which we will exit the loopifstart<=end:array[start],array[end]=array[end],array[start]# The loop continueselse:# We exit out of the loopbreakarray[low],array[end]=array[end],array[low]# As we got pivot element index is end# now pivot element is at its sorted position# return pivot element index (end)returnend# The main function that implements QuickSort# arr[] --> Array to be sorted,# low --> Starting index,# high --> Ending indexdefquick_sort(array,start,end):# If low is lesser than highifstart<end:# idx is index of pivot element which is at its# sorted positionidx=partition(array,start,end)# Separately sort elements before# partition and after partitionquick_sort(array,start,idx-1)quick_sort(array,idx+1,end)# Function to print an arraydefprint_arr(arr,n):foriinrange(n):print(arr[i],end=" ")print()# Driver Codearr1=[7,6,10,5,9,2,1,15,7]quick_sort(arr1,0,len(arr1)-1)print_arr(arr1,len(arr1))# This code is contributed by Aditya Sharma
C#
usingSystem;classQuickSort{/* This function takes first element as pivot, the function places the pivot element(first element) on its sorted position and all the element lesser than pivot will placed left to it, and all the element greater than pivot placed right to it.*/intpartition(int[]arr,intlow,inthigh){// First element as pivotintpivot=arr[low];intst=low;// st points to the starting of arrayintend=high;// end points to the ending of the arrayintk=high;for(inti=high;i>low;i--){if(arr[i]>pivot){swap(arr,i,k--);}}swap(arr,low,k);// As we got pivot element index is end// now pivot element is at its sorted position// return pivot element index (end)returnk;}// Function to swap two elementspublicstaticvoidswap(int[]arr,inti,intj){inttemp=arr[i];arr[i]=arr[j];arr[j]=temp;}/* The main function that implements QuickSort arr[] --> Array to be sorted, low --> Starting index, high --> Ending index */voidquickSort(int[]arr,intlow,inthigh){// If low is lesser than highif(low<high){// idx is index of pivot element which is at its// sorted positionintidx=partition(arr,low,high);// Separately sort elements before// partition and after partitionquickSort(arr,low,idx-1);quickSort(arr,idx+1,high);}}/* Function to print an array */voidprintArray(int[]arr,intsize){inti;for(i=0;i<size;i++)Console.Write(arr[i]+" ");Console.WriteLine();}// Driver CodepublicstaticvoidMain(){int[]arr={7,6,10,5,9,2,1,15,7};intn=arr.Length;QuickSortob=newQuickSort();ob.quickSort(arr,0,n-1);Console.WriteLine("Sorted array");ob.printArray(arr,n);}}
JavaScript
functionpartition(functionpartition(array,low,high){// First Element as pivotletpivot=array[low];// st points to the starting of arrayletstart=low+1;// end points to the ending of the arrayletend=high;while(true){// It indicates we have already moved all the elements to their correct side of the pivotwhile(start<=end&&array[end]>=pivot){end--;}// Opposite processwhile(start<=end&&array[start]<=pivot){start++;}// Case in which we will exit the loopif(start<=end){[array[start],array[end]]=[array[end],array[start]];// The loop continues}else{// We exit out of the loopbreak;}}[array[low],array[end]]=[array[end],array[low]];// As we got pivot element index is end// now pivot element is at its sorted position// return pivot element index (end)returnend;}functionquick_sort(array,start,end){// If low is lesser than highif(start<end){// idx is index of pivot element which is at its// sorted positionletidx=partition(array,start,end);// Separately sort elements before// partition and after partitionquick_sort(array,start,idx-1);quick_sort(array,idx+1,end);}}functionprint_arr(arr){console.log(arr.join(" "));}// Driver Codeletarr1=[7,6,10,5,9,2,1,15,7];quick_sort(arr1,0,arr1.length-1);console.log("Sorted array: ");print_arr(arr1);//contributed by Aditya Sharma
Output
Sorted array:
1 2 5 6 7 7 9 10 15
Complexity Analysis:
Time Complexity:
Average Case: O(N * logN), where N is the length of the array.