In this tutorial, you will learn how quicksort works. Additionally, you will discover working instances of quicksort in C, C++ Python, and Java.

What does Quicksort mean?

Quicksort is a popular sorting algorithm n that is frequently quicker in practice compared to other sorting algorithms. It uses a divide-and-conquer procedure to rapidly sort data items by dividing an enormous array into two smaller arrays. It was developed by Charles Antony Richard Hoare (usually known as C.A.R. Hoare or Tony Hoare) in 1960 for a project on the machine translation for the National Physical Laboratory.

What is Quick Sort?

Quick Sort algorithm follows Divide and Conquer approach. It divides elements into smaller parts dependent on some conditions and playing out the sort procedure on those divided smaller parts.

Quicksort is an algorithm dependent on the divide and conquer approach in which the array is part into subarrays and these sub-arrays are recursively called to sort the elements.


How QuickSort Works?

  1. A pivot element is chosen from the array. You can choose any element from the array as the pivot element.

Here, we have taken the furthest right (ie. the last element) of the array as the pivot element.

2. The elements less than the pivot element are put on the left and the elements greater than the pivot element are put on the right.

The above arrangement is accomplished by the accompanying steps.

a. A pointer is fixed at the pivot element. The pivot element is compared and the elements starting from the first index. On the off chance that the element greater than the pivot element is reached, a second pointer is set for that element.

b. Presently, the pivot element is compared and different elements (a third pointer). On the off chance that an element smaller than the pivot element is reached, the smaller element is swapped with the greater element discovered before.

c. The process goes on until the second last element is reached.

At last, the pivot element is swapped with the second pointer.

d. Presently the left and right subparts of this pivot element are taken for additional processing in the steps beneath.

3. Pivot elements are again chosen for the left and the right sub-parts independently. Inside these sub-parts, the pivot elements are set at their right position. At that point, stage 2 is repeated.

4. The sub-parts are again divided into smaller sub-parts until every subpart is formed of a single element.

5. Now, the array is as of now sorted.


Quicksort uses recursion for sorting the sub-parts.

Based on the Divide and conquer approach, the quicksort algorithm can be clarified as:

  • Divide

The array is divided into subparts taking pivot as the apportioning point. The elements less than the pivot are set to the left of the pivot and the elements greater than the pivot are put to the right.

  • Conquer

The left and the right subparts are again parceled using the by choosing pivot elements for them. This can be accomplished by recursively passing the subparts into the algorithm.

  • Combine

This progression doesn’t assume a critical part in quicksort. The array is now sorted toward the finish of the conquer step.

You can understand the working of quicksort with the assistance of the outlines underneath.


Quick Sort Algorithm

quickSort(array, leftmostIndex, rightmostIndex)
  if (leftmostIndex < rightmostIndex)
    pivotIndex <- partition(array,leftmostIndex, rightmostIndex)
    quickSort(array, leftmostIndex, pivotIndex)
    quickSort(array, pivotIndex + 1, rightmostIndex)

partition(array, leftmostIndex, rightmostIndex)
  set rightmostIndex as pivotIndex
  storeIndex <- leftmostIndex - 1
  for i <- leftmostIndex + 1 to rightmostIndex
  if element[i] < pivotElement
    swap element[i] and element[storeIndex]
    storeIndex++
  swap pivotElement and element[storeIndex+1]
return storeIndex + 1

Python, Java, and C/C++ Examples

Python

# Quick sort in Python


# Function to partition the array on the basis of pivot element
def partition(array, low, high):

    # Select the pivot element
    pivot = array[high]
    i = low - 1

    # Put the elements smaller than pivot on the left and greater 
    #than pivot on the right of pivot
    for j in range(low, high):
        if array[j] <= pivot:
            i = i + 1
            (array[i], array[j]) = (array[j], array[i])

    (array[i + 1], array[high]) = (array[high], array[i + 1])

    return i + 1


def quickSort(array, low, high):
    if low < high:

        # Select pivot position and put all the elements smaller 
        # than pivot on left and greater than pivot on right
        pi = partition(array, low, high)

        # Sort the elements on the left of pivot
        quickSort(array, low, pi - 1)

        # Sort the elements on the right of pivot
        quickSort(array, pi + 1, high)


data = [8, 7, 2, 1, 0, 9, 6]
size = len(data)
quickSort(data, 0, size - 1)
print('Sorted Array in Ascending Order:')
print(data)

Java

// Quick sort in Java

import java.util.Arrays;

class QuickSort {

  // Function to partition the array on the basis of pivot element
  int partition(int array[], int low, int high) {
    
    // Select the pivot element
    int pivot = array[high];
    int i = (low - 1);

    // Put the elements smaller than pivot on the left and 
    // greater than pivot on the right of pivot
    for (int j = low; j < high; j++) {
      if (array[j] <= pivot) {
        i++;
        int temp = array[i];
        array[i] = array[j];
        array[j] = temp;
      }
    }
    int temp = array[i + 1];
    array[i + 1] = array[high];
    array[high] = temp;
    return (i + 1);
  }

  void quickSort(int array[], int low, int high) {
    if (low < high) {

      // Select pivot position and put all the elements smaller 
      // than pivot on left and greater than pivot on right
      int pi = partition(array, low, high);
      
      // Sort the elements on the left of pivot
      quickSort(array, low, pi - 1);

      // Sort the elements on the right of pivot
      quickSort(array, pi + 1, high);
    }
  }

  // Driver code
  public static void main(String args[]) {
    int[] data = { 8, 7, 2, 1, 0, 9, 6 };
    int size = data.length;
    QuickSort qs = new QuickSort();
    qs.quickSort(data, 0, size - 1);
    System.out.println("Sorted Array in Ascending Order: ");
    System.out.println(Arrays.toString(data));
  }
}

C

// Quick sort in C

#include <stdio.h>

// Function to swap position of elements
void swap(int *a, int *b) {
  int t = *a;
  *a = *b;
  *b = t;
}

// Function to partition the array on the basis of pivot element
int partition(int array[], int low, int high) {
  
  // Select the pivot element
  int pivot = array[high];
  int i = (low - 1);

  // Put the elements smaller than pivot on the left 
  // and greater than pivot on the right of pivot
  for (int j = low; j < high; j++) {
    if (array[j] <= pivot) {
      i++;
      swap(&array[i], &array[j]);
    }
  }

  swap(&array[i + 1], &array[high]);
  return (i + 1);
}

void quickSort(int array[], int low, int high) {
  if (low < high) {
    
    // Select pivot position and put all the elements smaller 
    // than pivot on left and greater than pivot on right
    int pi = partition(array, low, high);
    
    // Sort the elements on the left of pivot
    quickSort(array, low, pi - 1);
    
    // Sort the elements on the right of pivot
    quickSort(array, pi + 1, high);
  }
}

// Function to print eklements of an array
void printArray(int array[], int size) {
  for (int i = 0; i < size; ++i) {
    printf("%d  ", array[i]);
  }
  printf("\n");
}

// Driver code
int main() {
  int data[] = {8, 7, 2, 1, 0, 9, 6};
  int n = sizeof(data) / sizeof(data[0]);
  quickSort(data, 0, n - 1);
  printf("Sorted array in ascending order: \n");
  printArray(data, n);
}

C++

// Quick sort in C++

#include <iostream>
using namespace std;

// Function to swap position of elements
void swap(int *a, int *b) {
  int t = *a;
  *a = *b;
  *b = t;
}

// Function to print eklements of an array
void printArray(int array[], int size) {
  int i;
  for (i = 0; i < size; i++)
    cout << array[i] << " ";
  cout << endl;
}

// Function to partition the array on the basis of pivot element
int partition(int array[], int low, int high) {
  // Select the pivot element
  int pivot = array[high];
  int i = (low - 1);

  // Put the elements smaller than pivot on the left 
  // and greater than pivot on the right of pivot
  for (int j = low; j < high; j++) {
    if (array[j] <= pivot) {
      i++;
      swap(&array[i], &array[j]);
    }
  }
  printArray(array, 7);
  cout << "........\n";
  swap(&array[i + 1], &array[high]);
  return (i + 1);
}

void quickSort(int array[], int low, int high) {
  if (low < high) {
    // Select pivot position and put all the elements smaller 
    // than pivot on left and greater than pivot on right
    int pi = partition(array, low, high);

    // Sort the elements on the left of pivot
    quickSort(array, low, pi - 1);

    // Sort the elements on the right of pivot
    quickSort(array, pi + 1, high);
  }
}

// Driver code
int main() {
  int data[] = {8, 7, 6, 1, 0, 9, 2};
  int n = sizeof(data) / sizeof(data[0]);
  quickSort(data, 0, n - 1);
  cout << "Sorted array in ascending order: \n";
  printArray(data, n);
}

Quicksort Complexity

Time Complexities

Worst Case Complexity [Big-O]: O(n2)

It happens when the pivot element picked is either the greatest or the smallest element.

This condition leads to the case wherein the pivot element lies in an extraordinary finish of the sorted array. One sub-array is consistently vacant and another sub-array contains n – 1 element. Subsequently, quicksort is called uniquely on this sub-array.

Be that as it may, the fast sort algorithm has better execution for scattered pivots.

  • Best Case Complexity [Big-omega]: O(n*log n)

It happens when the pivot element is consistently the center element or close to the center element.

  • Average Case Complexity [Big-theta]: O(n*log n)

It happens when the above conditions don’t happen.

Space Complexity

The space complexity for quicksort is O(log n).


Quicksort Applications

Quicksort is actualized when

  • the programming language is useful for recursion
  • time complexity matters
  • space complexity matters

Thanks for reading! We hope you found this tutorial helpful and we would love to hear your feedback in the Comments section below. And show us what you’ve learned by sharing your photos and creative projects with us.