Open In App

Iterative Quick Sort

Last Updated : 22 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Following is a typical recursive implementation of Quick Sort that uses last element as pivot. 
 

C++
// CPP code for recursive function of Quicksort 
#include <bits/stdc++.h> 
using namespace std; 

/* This function takes last element as pivot, 
places the pivot element at its correct 
position in sorted array, and places 
all smaller (smaller than pivot) to left 
of pivot and all greater elements to 
right of pivot */
int partition(int arr[], int l, int h) 
{ 
    int x = arr[h]; 
    int i = (l - 1); 

    for (int j = l; j <= h - 1; j++) { 
        if (arr[j] <= x) { 
            i++; 
            swap(arr[i], arr[j]); 
        } 
    } 
    swap(arr[i + 1], arr[h]); 
    return (i + 1); 
} 

/* A[] --> Array to be sorted, 
l --> Starting index, 
h --> Ending index */
void quickSort(int A[], int l, int h) 
{ 
    if (l < h) { 
        /* Partitioning index */
        int p = partition(A, l, h); 
        quickSort(A, l, p - 1); 
        quickSort(A, p + 1, h); 
    } 
} 

// Driver code 
int main() 
{ 

    int n = 5; 
    int arr[n] = { 4, 2, 6, 9, 2 }; 

    quickSort(arr, 0, n - 1); 

    for (int i = 0; i < n; i++) { 
        cout << arr[i] << " "; 
    } 

    return 0; 
} 
Java
// Java program for implementation of QuickSort
import java.util.*;

class QuickSort {
    /* This function takes last element as pivot,
    places the pivot element at its correct
    position in sorted array, and places all
    smaller (smaller than pivot) to left of
    pivot and all greater elements to right
    of pivot */
    static int partition(int arr[], int low, int high)
    {
        int pivot = arr[high];
        int i = (low - 1); // index of smaller element
        for (int j = low; j <= high - 1; j++) {
            // If current element is smaller than or
            // equal to pivot
            if (arr[j] <= pivot) {
                i++;

                // swap arr[i] and arr[j]
                int temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }

        // swap arr[i+1] and arr[high] (or pivot)
        int temp = arr[i + 1];
        arr[i + 1] = arr[high];
        arr[high] = temp;

        return i + 1;
    }

    /* The main function that implements QuickSort()
    arr[] --> Array to be sorted,
    low --> Starting index,
    high --> Ending index */
    static void qSort(int arr[], int low, int high)
    {
        if (low < high) {
            /* pi is partitioning index, arr[pi] is
            now at right place */
            int pi = partition(arr, low, high);

            // Recursively sort elements before
            // partition and after partition
            qSort(arr, low, pi - 1);
            qSort(arr, pi + 1, high);
        }
    }

    // Driver code
    public static void main(String args[])
    {

        int n = 5;
        int arr[] = { 4, 2, 6, 9, 2 };

        qSort(arr, 0, n - 1);

        for (int i = 0; i < n; i++) {
            System.out.print(arr[i] + " ");
        }
    }
}
Python
# A typical recursive Python
# implementation of QuickSort

# Function takes last element as pivot,
# places the pivot element at its correct
# position in sorted array, and places all
# smaller (smaller than pivot) to left of
# pivot and all greater elements to right
# of pivot
def partition(arr, low, high):
    i = (low - 1)         # index of smaller element
    pivot = arr[high]     # pivot

    for j in range(low, high):

        # If current element is smaller 
        # than or equal to pivot
        if arr[j] <= pivot:
        
            # increment index of
            # smaller element
            i += 1
            arr[i], arr[j] = arr[j], arr[i]

    arr[i + 1], arr[high] = arr[high], arr[i + 1]
    return (i + 1)

# The main function that implements QuickSort
# arr[] --> Array to be sorted,
# low --> Starting index,
# high --> Ending index

# Function to do Quick sort
def quickSort(arr, low, high):
    if low < high:

        # pi is partitioning index, arr[p] is now
        # at right place
        pi = partition(arr, low, high)

        # Separately sort elements before
        # partition and after partition
        quickSort(arr, low, pi-1)
        quickSort(arr, pi + 1, high)

# Driver Code
if __name__ == '__main__' :
    
    arr = [4, 2, 6, 9, 2]
    n = len(arr)
    
    # Calling quickSort function
    quickSort(arr, 0, n - 1)
    
    for i in range(n):
        print(arr[i], end = " ")
C#
// C# program for implementation of
// QuickSort
using System;

class GFG {

    /* This function takes last element
    as pivot, places the pivot element
    at its correct position in sorted
    array, and places all smaller 
    (smaller than pivot) to left of
    pivot and all greater elements to 
    right of pivot */
    static int partition(int[] arr,
                         int low, int high)
    {
        int temp;
        int pivot = arr[high];

        // index of smaller element
        int i = (low - 1);
        for (int j = low; j <= high - 1; j++) {

            // If current element is
            // smaller than or
            // equal to pivot
            if (arr[j] <= pivot) {
                i++;

                // swap arr[i] and arr[j]
                temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }

        // swap arr[i+1] and arr[high]
        // (or pivot)
        temp = arr[i + 1];
        arr[i + 1] = arr[high];
        arr[high] = temp;

        return i + 1;
    }

    /* The main function that implements
    QuickSort() arr[] --> Array to be 
    sorted,
    low --> Starting index,
    high --> Ending index */
    static void qSort(int[] arr, int low,
                      int high)
    {
        if (low < high) {
            /* pi is partitioning index, 
            arr[pi] is now at right place */
            int pi = partition(arr, low, high);

            // Recursively sort elements
            // before partition and after
            // partition
            qSort(arr, low, pi - 1);
            qSort(arr, pi + 1, high);
        }
    }

    // Driver code
    public static void Main()
    {

        int n = 5;
        int[] arr = { 4, 2, 6, 9, 2 };

        qSort(arr, 0, n - 1);

        for (int i = 0; i < n; i++)
            Console.Write(arr[i] + " ");
    }
}

// This code is contributed by nitin mittal.
JavaScript
<script>

    // JavaScript program for implementation of QuickSort
    
    /* This function takes last element
    as pivot, places the pivot element
    at its correct position in sorted
    array, and places all smaller 
    (smaller than pivot) to left of
    pivot and all greater elements to 
    right of pivot */
    function partition(arr, low, high)
    {
        let temp;
        let pivot = arr[high];
  
        // index of smaller element
        let i = (low - 1);
        for (let j = low; j <= high - 1; j++) {
  
            // If current element is
            // smaller than or
            // equal to pivot
            if (arr[j] <= pivot) {
                i++;
  
                // swap arr[i] and arr[j]
                temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }
  
        // swap arr[i+1] and arr[high]
        // (or pivot)
        temp = arr[i + 1];
        arr[i + 1] = arr[high];
        arr[high] = temp;
  
        return i + 1;
    }
  
    /* The main function that implements
    QuickSort() arr[] --> Array to be 
    sorted,
    low --> Starting index,
    high --> Ending index */
    function qSort(arr, low, high)
    {
        if (low < high) {
            /* pi is partitioning index, 
            arr[pi] is now at right place */
            let pi = partition(arr, low, high);
  
            // Recursively sort elements
            // before partition and after
            // partition
            qSort(arr, low, pi - 1);
            qSort(arr, pi + 1, high);
        }
    }
    
    let n = 5;
    let arr = [ 4, 2, 6, 9, 2 ];

    qSort(arr, 0, n - 1);

    for (let i = 0; i < n; i++)
      document.write(arr[i] + " ");
  
</script>
PHP
<?php
// PHP code for recursive function 
// of Quicksort 

// Function to swap numbers 
function swap(&$a, &$b)
{ 
    $temp = $a; 
    $a = $b; 
    $b = $temp; 
} 

/* This function takes last element as pivot, 
places the pivot element at its correct 
position in sorted array, and places 
all smaller (smaller than pivot) to left 
of pivot and all greater elements to 
right of pivot */
function partition (&$arr, $l, $h) 
{ 
    $x = $arr[$h]; 
    $i = ($l - 1); 

    for ($j = $l; $j <= $h - 1; $j++) 
    { 
        if ($arr[$j] <= $x) 
        { 
            $i++; 
            swap ($arr[$i], $arr[$j]); 
        } 
    } 
    swap ($arr[$i + 1], $arr[$h]); 
    return ($i + 1); 
} 

/* A[] --> Array to be sorted, 
l --> Starting index, 
h --> Ending index */
function quickSort(&$A, $l, $h) 
{ 
    if ($l < $h) 
    { 
        /* Partitioning index */
        $p = partition($A, $l, $h); 
        quickSort($A, $l, $p - 1); 
        quickSort($A, $p + 1, $h); 
    } 
    
} 

// Driver code 
$n = 5; 
$arr = array(4, 2, 6, 9, 2); 

quickSort($arr, 0, $n - 1); 

for($i = 0; $i < $n; $i++)
{ 
    echo $arr[$i] . " "; 
} 

// This code is contributed by
// rathbhupendra
?>

Output:  

2 2 4 6 9


The above implementation can be optimized in many ways
1) The above implementation uses the last index as a pivot. This causes worst-case behavior on already sorted arrays, which is a commonly occurring case. The problem can be solved by choosing either a random index for the pivot or choosing the middle index of the partition or choosing the median of the first, middle, and last element of the partition for the pivot. (See this for details)
2) To reduce the recursion depth, recur first for the smaller half of the array, and use a tail call to recurse into the other. 
3) Insertion sort works better for small subarrays. Insertion sort can be used for invocations on such small arrays (i.e. where the length is less than a threshold t determined experimentally). For example, this library implementation of Quicksort uses insertion sort below size 7. 
Despite the above optimizations, the function remains recursive and uses function call stack to store intermediate values of l and h. The function call stack stores other bookkeeping information together with parameters. Also, function calls involve overheads like storing activation records of the caller function and then resuming execution. 
The above function can be easily converted to an iterative version with the help of an auxiliary stack. Following is an iterative implementation of the above recursive code. 
 

C++
// An iterative implementation of quick sort 
#include <bits/stdc++.h> 
using namespace std; 

/* This function is same in both iterative and recursive*/
int partition(int arr[], int l, int h) 
{ 
    int x = arr[h]; 
    int i = (l - 1); 

    for (int j = l; j <= h - 1; j++) { 
        if (arr[j] <= x) { 
            i++; 
            swap(arr[i], arr[j]); 
        } 
    } 
    swap(arr[i + 1], arr[h]); 
    return (i + 1); 
} 

/* A[] --> Array to be sorted, 
l --> Starting index, 
h --> Ending index */
void quickSortIterative(int arr[], int l, int h) 
{ 
    // Create an auxiliary stack 
    int stack[h - l + 1]; 

    // initialize top of stack 
    int top = -1; 

    // push initial values of l and h to stack 
    stack[++top] = l; 
    stack[++top] = h; 

    // Keep popping from stack while is not empty 
    while (top >= 0) { 
        // Pop h and l 
        h = stack[top--]; 
        l = stack[top--]; 

        // Set pivot element at its correct position 
        // in sorted array 
        int p = partition(arr, l, h); 

        // If there are elements on left side of pivot, 
        // then push left side to stack 
        if (p - 1 > l) { 
            stack[++top] = l; 
            stack[++top] = p - 1; 
        } 

        // If there are elements on right side of pivot, 
        // then push right side to stack 
        if (p + 1 < h) { 
            stack[++top] = p + 1; 
            stack[++top] = h; 
        } 
    } 
} 

// A utility function to print contents of arr 
void printArr(int arr[], int n) 
{ 
    int i; 
    for (i = 0; i < n; ++i) 
        cout << arr[i] << " "; 
} 

// Driver code 
int main() 
{ 
    int arr[] = { 4, 3, 5, 2, 1, 3, 2, 3 }; 
    int n = sizeof(arr) / sizeof(*arr); 
    quickSortIterative(arr, 0, n - 1); 
    printArr(arr, n); 
    return 0; 
} 

// This is code is contributed by rathbhupendra 
C
// An iterative implementation of quick sort
#include <stdio.h>

// A utility function to swap two elements
void swap(int* a, int* b)
{
    int t = *a;
    *a = *b;
    *b = t;
}

/* This function is same in both iterative and recursive*/
int partition(int arr[], int l, int h)
{
    int x = arr[h];
    int i = (l - 1);

    for (int j = l; j <= h - 1; j++) {
        if (arr[j] <= x) {
            i++;
            swap(&arr[i], &arr[j]);
        }
    }
    swap(&arr[i + 1], &arr[h]);
    return (i + 1);
}

/* A[] --> Array to be sorted, 
   l  --> Starting index, 
   h  --> Ending index */
void quickSortIterative(int arr[], int l, int h)
{
    // Create an auxiliary stack
    int stack[h - l + 1];

    // initialize top of stack
    int top = -1;

    // push initial values of l and h to stack
    stack[++top] = l;
    stack[++top] = h;

    // Keep popping from stack while is not empty
    while (top >= 0) {
        // Pop h and l
        h = stack[top--];
        l = stack[top--];

        // Set pivot element at its correct position
        // in sorted array
        int p = partition(arr, l, h);

        // If there are elements on left side of pivot,
        // then push left side to stack
        if (p - 1 > l) {
            stack[++top] = l;
            stack[++top] = p - 1;
        }

        // If there are elements on right side of pivot,
        // then push right side to stack
        if (p + 1 < h) {
            stack[++top] = p + 1;
            stack[++top] = h;
        }
    }
}

// A utility function to print contents of arr
void printArr(int arr[], int n)
{
    int i;
    for (i = 0; i < n; ++i)
        printf("%d ", arr[i]);
}

// Driver program to test above functions
int main()
{
    int arr[] = { 4, 3, 5, 2, 1, 3, 2, 3 };
    int n = sizeof(arr) / sizeof(*arr);
    quickSortIterative(arr, 0, n - 1);
    printArr(arr, n);
    return 0;
}
Java
// Java program for implementation of QuickSort
import java.util.*;

class QuickSort {
    /* This function takes last element as pivot,
    places the pivot element at its correct
    position in sorted array, and places all
    smaller (smaller than pivot) to left of
    pivot and all greater elements to right
    of pivot */
    static int partition(int arr[], int low, int high)
    {
        int pivot = arr[high];

        // index of smaller element
        int i = (low - 1);
        for (int j = low; j <= high - 1; j++) {
            // If current element is smaller than or
            // equal to pivot
            if (arr[j] <= pivot) {
                i++;

                // swap arr[i] and arr[j]
                int temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }

        // swap arr[i+1] and arr[high] (or pivot)
        int temp = arr[i + 1];
        arr[i + 1] = arr[high];
        arr[high] = temp;

        return i + 1;
    }

    /* A[] --> Array to be sorted, 
   l  --> Starting index, 
   h  --> Ending index */
    static void quickSortIterative(int arr[], int l, int h)
    {
        // Create an auxiliary stack
        int[] stack = new int[h - l + 1];

        // initialize top of stack
        int top = -1;

        // push initial values of l and h to stack
        stack[++top] = l;
        stack[++top] = h;

        // Keep popping from stack while is not empty
        while (top >= 0) {
            // Pop h and l
            h = stack[top--];
            l = stack[top--];

            // Set pivot element at its correct position
            // in sorted array
            int p = partition(arr, l, h);

            // If there are elements on left side of pivot,
            // then push left side to stack
            if (p - 1 > l) {
                stack[++top] = l;
                stack[++top] = p - 1;
            }

            // If there are elements on right side of pivot,
            // then push right side to stack
            if (p + 1 < h) {
                stack[++top] = p + 1;
                stack[++top] = h;
            }
        }
    }
    // Driver code
    public static void main(String args[])
    {
        int arr[] = { 4, 3, 5, 2, 1, 3, 2, 3 };
        int n = 8;

        // Function calling
        quickSortIterative(arr, 0, n - 1);

        for (int i = 0; i < n; i++) {
            System.out.print(arr[i] + " ");
        }
    }
}
Python
# Python program for implementation of Quicksort 

# This function is same in both iterative and recursive
def partition(arr, l, h):
    i = ( l - 1 )
    x = arr[h]

    for j in range(l, h):
        if   arr[j] <= x:

            # increment index of smaller element
            i = i + 1
            arr[i], arr[j] = arr[j], arr[i]

    arr[i + 1], arr[h] = arr[h], arr[i + 1]
    return (i + 1)

# Function to do Quick sort
# arr[] --> Array to be sorted,
# l  --> Starting index,
# h  --> Ending index
def quickSortIterative(arr, l, h):

    # Create an auxiliary stack
    size = h - l + 1
    stack = [0] * (size)

    # initialize top of stack
    top = -1

    # push initial values of l and h to stack
    top = top + 1
    stack[top] = l
    top = top + 1
    stack[top] = h

    # Keep popping from stack while is not empty
    while top >= 0:

        # Pop h and l
        h = stack[top]
        top = top - 1
        l = stack[top]
        top = top - 1

        # Set pivot element at its correct position in
        # sorted array
        p = partition( arr, l, h )

        # If there are elements on left side of pivot,
        # then push left side to stack
        if p-1 > l:
            top = top + 1
            stack[top] = l
            top = top + 1
            stack[top] = p - 1

        # If there are elements on right side of pivot,
        # then push right side to stack
        if p + 1 < h:
            top = top + 1
            stack[top] = p + 1
            top = top + 1
            stack[top] = h

# Driver code to test above
arr = [4, 3, 5, 2, 1, 3, 2, 3]
n = len(arr)
quickSortIterative(arr, 0, n-1)
print ("Sorted array is:")
for i in range(n):
    print ("% d" % arr[i]),

# This code is contributed by Mohit Kumra
C#
// C# program for implementation of QuickSort
using System;

class GFG {

    /* This function takes last element as pivot,
    places the pivot element at its correct
    position in sorted array, and places all
    smaller (smaller than pivot) to left of
    pivot and all greater elements to right
    of pivot */
    static int partition(int[] arr, int low,
                         int high)
    {
        int temp;
        int pivot = arr[high];

        // index of smaller element
        int i = (low - 1);
        for (int j = low; j <= high - 1; j++) {
            // If current element is smaller
            // than or equal to pivot
            if (arr[j] <= pivot) {
                i++;

                // swap arr[i] and arr[j]
                temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }

        // swap arr[i+1] and arr[high]
        // (or pivot)

        temp = arr[i + 1];
        arr[i + 1] = arr[high];
        arr[high] = temp;

        return i + 1;
    }

    /* A[] --> Array to be sorted, 
    l --> Starting index, 
    h --> Ending index */
    static void quickSortIterative(int[] arr,
                                   int l, int h)
    {
        // Create an auxiliary stack
        int[] stack = new int[h - l + 1];

        // initialize top of stack
        int top = -1;

        // push initial values of l and h to
        // stack
        stack[++top] = l;
        stack[++top] = h;

        // Keep popping from stack while
        // is not empty
        while (top >= 0) {
            // Pop h and l
            h = stack[top--];
            l = stack[top--];

            // Set pivot element at its
            // correct position in
            // sorted array
            int p = partition(arr, l, h);

            // If there are elements on
            // left side of pivot, then
            // push left side to stack
            if (p - 1 > l) {
                stack[++top] = l;
                stack[++top] = p - 1;
            }

            // If there are elements on
            // right side of pivot, then
            // push right side to stack
            if (p + 1 < h) {
                stack[++top] = p + 1;
                stack[++top] = h;
            }
        }
    }

    // Driver code
    public static void Main()
    {
        int[] arr = { 4, 3, 5, 2, 1, 3, 2, 3 };
        int n = 8;

        // Function calling
        quickSortIterative(arr, 0, n - 1);

        for (int i = 0; i < n; i++)
            Console.Write(arr[i] + " ");
    }
}

// This code is contributed by anuj_67.
JavaScript
<script>
    // Javascript program for implementation of QuickSort
    
    /* This function takes last element as pivot,
    places the pivot element at its correct
    position in sorted array, and places all
    smaller (smaller than pivot) to left of
    pivot and all greater elements to right
    of pivot */
    function partition(arr, low, high)
    {
        let temp;
        let pivot = arr[high];
 
        // index of smaller element
        let i = (low - 1);
        for (let j = low; j <= high - 1; j++) {
            // If current element is smaller
            // than or equal to pivot
            if (arr[j] <= pivot) {
                i++;
 
                // swap arr[i] and arr[j]
                temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }
 
        // swap arr[i+1] and arr[high]
        // (or pivot)
 
        temp = arr[i + 1];
        arr[i + 1] = arr[high];
        arr[high] = temp;
 
        return i + 1;
    }
 
    /* A[] --> Array to be sorted,
    l --> Starting index,
    h --> Ending index */
    function quickSortIterative(arr, l, h)
    {
        // Create an auxiliary stack
        let stack = new Array(h - l + 1);
        stack.fill(0);
 
        // initialize top of stack
        let top = -1;
 
        // push initial values of l and h to
        // stack
        stack[++top] = l;
        stack[++top] = h;
 
        // Keep popping from stack while
        // is not empty
        while (top >= 0) {
            // Pop h and l
            h = stack[top--];
            l = stack[top--];
 
            // Set pivot element at its
            // correct position in
            // sorted array
            let p = partition(arr, l, h);
 
            // If there are elements on
            // left side of pivot, then
            // push left side to stack
            if (p - 1 > l) {
                stack[++top] = l;
                stack[++top] = p - 1;
            }
 
            // If there are elements on
            // right side of pivot, then
            // push right side to stack
            if (p + 1 < h) {
                stack[++top] = p + 1;
                stack[++top] = h;
            }
        }
    }
    
    let arr = [ 4, 3, 5, 2, 1, 3, 2, 3 ];
    let n = 8;

    // Function calling
    quickSortIterative(arr, 0, n - 1);

    for (let i = 0; i < n; i++)
      document.write(arr[i] + " ");

// This code is contributed by mukesh07.
</script>
PHP
<?php
// An iterative implementation of quick sort 

// A utility function to swap two elements 
function swap ( &$a, &$b ) 
{ 
    $t = $a; 
    $a = $b; 
    $b = $t; 
} 

/* This function is same in both iterative and recursive*/
function partition (&$arr, $l, $h) 
{ 
    $x = $arr[$h]; 
    $i = ($l - 1); 

    for ($j = $l; $j <= $h- 1; $j++) 
    { 
        if ($arr[$j] <= $x) 
        { 
            $i++; 
            swap ($arr[$i], $arr[$j]); 
        } 
    } 
    swap ($arr[$i + 1], $arr[$h]); 
    return ($i + 1); 
} 

/* A[] --> Array to be sorted, 
l --> Starting index, 
h --> Ending index */
function quickSortIterative (&$arr, $l, $h) 
{ 
    // Create an auxiliary stack 
    $stack=array_fill(0, $h - $l + 1, 0); 

    // initialize top of stack 
    $top = -1; 

    // push initial values of l and h to stack 
    $stack[ ++$top ] = $l; 
    $stack[ ++$top ] = $h; 

    // Keep popping from stack while is not empty 
    while ( $top >= 0 ) 
    { 
        // Pop h and l 
        $h = $stack[ $top-- ]; 
        $l = $stack[ $top-- ]; 

        // Set pivot element at its correct position 
        // in sorted array 
        $p = partition( $arr, $l, $h ); 

        // If there are elements on left side of pivot, 
        // then push left side to stack 
        if ( $p-1 > $l ) 
        { 
            $stack[ ++$top ] = $l; 
            $stack[ ++$top ] = $p - 1; 
        } 

        // If there are elements on right side of pivot, 
        // then push right side to stack 
        if ( $p+1 < $h ) 
        { 
            $stack[ ++$top ] = $p + 1; 
            $stack[ ++$top ] = $h; 
        } 
    } 
} 

// A utility function to print contents of arr 
function printArr( $arr, $n ) 
{ 
    for ( $i = 0; $i < $n; ++$i ) 
        echo $arr[$i]." "; 
} 

// Driver code 
    $arr = array(4, 3, 5, 2, 1, 3, 2, 3); 
    $n = count($arr); 
    quickSortIterative($arr, 0, $n - 1 ); 
    printArr($arr, $n ); 

// This is code is contributed by chandan_jnu
?>


 

Output: 

1 2 2 3 3 3 4 5

Time Complexity: O(n*log(n))
Auxiliary Space: O(n)


The above-mentioned optimizations for recursive quicksort can also be applied to the iterative version.
1) Partition process is the same in both recursive and iterative. The same techniques to choose optimal pivot can also be applied to the iterative version.
2) To reduce the stack size, first push the indexes of smaller half.
3) Use insertion sort when the size reduces below an experimentally calculated threshold.
References: 
http://en.wikipedia.org/wiki/Quicksort
This article is compiled by Aashish Barnwal and reviewed by GeeksforGeeks team.
 



Previous Article
Next Article

Similar Reads

Why Quick Sort preferred for Arrays and Merge Sort for Linked Lists?
Why is Quick Sort preferred for arrays? Below are recursive and iterative implementations of Quick Sort and Merge Sort for arrays. Recursive Quick Sort for array. Iterative Quick Sort for arrays. Recursive Merge Sort for arrays Iterative Merge Sort for arrays Quick Sort in its general form is an in-place sort (i.e. it doesn't require any extra stor
5 min read
Bucket Sort vs Quick Sort
Bucket Sort and Quick Sort are two different sorting algorithms, each with its own characteristics, advantages, and disadvantages. In this article, we will provide a detailed overview of all the differences between Bucket Sort and Quick Sort. Bucket Sort:Bucket Sort is a non-comparison sorting algorithm that divides the input array into a number of
3 min read
Quick Sort vs Merge Sort
Quick sort first partitions the array and then make two recursive calls. Merge sort first makes recursive calls for the two halves, and then merges the two sorted halves. The following are differences between the two sorting algorithms. Partition of elements in the array : In the merge sort, the array is parted into just 2 halves (i.e. n/2). wherea
3 min read
Iterative Deepening Search(IDS) or Iterative Deepening Depth First Search(IDDFS)
There are two common ways to traverse a graph, BFS and DFS. Considering a Tree (or Graph) of huge height and width, both BFS and DFS are not very efficient due to following reasons. DFS first traverses nodes going through one adjacent of root, then next adjacent. The problem with this approach is, if there is a node close to root, but not in first
10 min read
p5.js | Quick Sort
QuickSort 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 quickSort that pick pivot in different ways. Always pick first element as pivot. Always pick last element as pivot. Pick a random element as pivot. Pick median as pivot. Approach: Fir
3 min read
Advanced Quick Sort (Hybrid Algorithm)
Prerequisites: Insertion Sort, Quick Sort, Selection SortIn this article, a Hybrid algorithm with the combination of quick sort and insertion sort is implemented. As the name suggests, the Hybrid algorithm combines more than one algorithm. Why Hybrid algorithm: Quicksort algorithm is efficient if the size of the input is very large. But, insertion
9 min read
Visualization of Quick sort using Matplotlib
Visualizing algorithms makes it easier to understand them by analyzing and comparing the number of operations that took place to compare and swap the elements. For this we will use matplotlib, to plot bar graphs to represent the elements of the array, Approach : We will generate an array with random elements.The algorithm will be called on that arr
3 min read
3D Visualisation of Quick Sort using Matplotlib in Python
Visualizing algorithms makes it easier to understand them by analyzing and comparing the number of operations that took place to compare and swap the elements. 3D visualization of algorithms is less common, for this we will use Matplotlib to plot bar graphs and animate them to represent the elements of the array. Let's see the 3D Visualizations of
3 min read
Improvement on the Quick Sort Algorithm
Prerequisite: QuickSort Algorithm The quicksort algorithm discussed in this article can take O(N2) time in the worst case. Hence, certain variations are needed which can efficiently partition the array and rearrange the elements around the pivot. Single Pivot Partitioning: In single pivot partitioning the array A[] can be divided into {A[p], A[p +
6 min read
Quick Sort(Hoare's Partition) Visualization using JavaScript
[video width="786" height="514" mp4="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20210225121659/hoare.mp4"][/video]GUI(Graphical User Interface) helps in better understanding than programs. In this article, we will visualize Quick Sort using JavaScript. We will see how the array is being partitioned into two parts and how we get the fina
4 min read
Quick Sort(Lomuto Partition) Visualization using JavaScript
GUI(Graphical User Interface) helps in better in understanding than programs. In this article, we will visualize Quick Sort using JavaScript. We will see how the array is being partitioned using Lomuto Partition and then how we get the final sorted array. We will also visualize the time complexity of Quick Sort. Reference: Quick SortLomuto Partitio
4 min read
Is Quick Sort Algorithm Adaptive or not
Pre-Requisites: Quick Sort Algorithm Adaptiveness in the Quick Sort Algorithm refers to the decision that if we are given an array that is already sorted, then the operations should be Performed or Not, i.e., if the number of operations performed on sorted Array is Not Equal to the operations performed on unsorted Array, then the Algorithm is known
8 min read
Some Frequently Asked Questions (FAQs) about Quick Sort
Below are some of the most frequently asked questions on Quick Sort: 1. Hoare's vs Lomuto PartitionPlease note that the above implementation is Lomuto Partition. A more optimized implementation of QuickSort is Hoare's partition which is more efficient than Lomuto's partition scheme because it does three times less swaps on average. 2. How to pick a
2 min read
Quick Sort using Multi-threading
QuickSort is a popular sorting technique based on divide and conquer algorithm. In this technique, an element is chosen as a pivot and the array is partitioned around it. The target of partition is, given an array and an element x of the array as a pivot, put x at its correct position in a sorted array and put all smaller elements (smaller than x)
9 min read
How do you avoid a worst case algorithm for a quick sort?
QuickSort is a popular and efficient sorting algorithm that relies on a divide-and-conquer strategy to sort a list of elements. It is widely used in various computer science applications due to its average-case time complexity of O(n log n), making it one of the fastest sorting algorithms available. However, QuickSort's performance can degrade to a
6 min read
Nuts & Bolts Problem (Lock & Key problem) using Quick Sort
Given a set of n nuts of different sizes and n bolts of different sizes. There is a one-one mapping between nuts and bolts. Match nuts and bolts efficiently. Constraint: Comparison of a nut to another nut or a bolt to another bolt is not allowed. It means a nut can only be compared with a bolt and a bolt can only be compared with a nut to see which
12 min read
Top Interview Questions and Answers on Quick Sort
Quick Sort is a popular sorting algorithm used in computer science. In our article "Top Interview Questions and Answers on Quick Sort", we present a collection of essential coding challenges focused on Quick Sort algorithms. These problems are carefully selected to help you sharpen your problem-solving skills and prepare effectively for interviews.
7 min read
Time and Space Complexity Analysis of Quick Sort
The time complexity of Quick Sort is O(n log n) on average case, but can become O(n^2) in the worst-case. The space complexity of Quick Sort in the best case is O(log n), while in the worst-case scenario, it becomes O(n) due to unbalanced partitioning causing a skewed recursion tree that requires a call stack of size O(n). VariationTime ComplexityS
4 min read
Quick Sort
QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. Table of Content How does QuickSort Algorithm work? Working of Partition Algorithm with IllustrationIllustration of QuickSort Algor
13 min read
Iterative Merge Sort
Following is a typical recursive implementation of Merge Sort C/C++ Code // Recursive C++ program for merge sort #include<bits/stdc++.h> using namespace std; // Function to merge the two haves // arr[l..m] and arr[m+1..r] of array arr[] void merge(int arr[], int l, int m, int r); // l is for left index and r is // right index of the sub-array
15+ min read
Iterative selection sort for linked list
Given a linked list, the task is to sort the linked list in non-decreasing order by using selection sort.Examples: Input : Linked List = 5 ->3 ->4 ->1 ->2Output : 1 ->2 ->3 ->4 ->5 Input : Linked List = 5 ->4 ->3 ->2Output : 2 ->3 ->4 ->5 Table of Content [Expected Approach - 1] Swapping node Values - O(n^2
15+ min read
Iterative Merge Sort for Linked List
Given a singly linked list of integers, the task is to sort it using iterative merge sort. Examples: Input: 40 -> 20 -> 60 -> 10 -> 50 -> 30 -> NULLOutput: 10 -> 20 -> 30 -> 40 -> 50 -> 60 -> NULL Input: 9 -> 5 -> 2 -> 8 -> NULLOutput: 2 -> 5 -> 8 -> 9 -> NULL Merge Sort is often preferred
14 min read
Tag sort or Bucket sort or Bin sort in Python
Tag sort, also known as Bucket sort or Bin sort, is a non-comparison based sorting algorithm that distributes elements of an array into a number of "buckets", and then sorts each bucket individually. Tag sort or Bucket sort or Bin sort Algorithm:Determine Range:Find the maximum and minimum values in the input array to determine the range of tags ne
2 min read
Comparison among Bubble Sort, Selection Sort and Insertion Sort
Bubble Sort, Selection Sort, and Insertion Sort are simple sorting algorithms that are commonly used to sort small datasets or as building blocks for more complex sorting algorithms. Here's a comparison of the three algorithms: Bubble Sort:Time complexity: O(n^2) in the worst and average cases, O(n) in the best case (when the input array is already
15 min read
A Quick Guide on DSA and Competitive Coding in Java
Data Structures and Algorithms (DSA) are the building blocks of efficient and optimized software solutions, especially in the realm of competitive coding. In this quick guide, we'll explore key concepts of DSA using Java, a versatile and widely used programming language. Table of Content Arrays In Java:Strings In Java:Stack in Java:Queue in Java: L
11 min read
Median of an unsorted array using Quick Select Algorithm
Given an unsorted array arr[] of length N, the task is to find the median of this array. Median of a sorted array of size N is defined as the middle element when n is odd and average of middle two elements when n is even. Examples: Input: arr[] = {12, 3, 5, 7, 4, 19, 26} Output: 7 Sorted sequence of given array arr[] = {3, 4, 5, 7, 12, 19, 26} Sinc
13 min read
Quick ways to check for Prime and find next Prime in Java
Many programming contest problems are somehow related Prime Numbers. Either we are required to check Prime Numbers, or we are asked to perform certain functions for all prime number between 1 to N. Example: Calculate the sum of all prime numbers between 1 and 1000000. Java provides two function under java.math.BigInteger to deal with Prime Numbers.
2 min read
Quick way to check if all the characters of a string are same
Given a string, check if all the characters of the string are the same or not. Examples: Input : s = "geeks"Output : No Input : s = "gggg" Output : Yes Recommended PracticeCheck StringTry It! Simple Way To find whether a string has all the same characters. Traverse the whole string from index 1 and check whether that character matches the first cha
8 min read
Quick Select in Python
Quick Select is an efficient algorithm for finding the k-th smallest (or largest) element in an unordered list. It is a variation of the QuickSort algorithm and works by repeatedly partitioning the input array around a pivot element until the desired element is found. Quick Select Algorithm:Quick Select Algorithm is a variation of QuickSort. The di
4 min read
How to Calculate Standard Deviation in Excel: Quick Guide with Formulas and Examples
Understanding standard deviation in Excel is crucial for anyone looking to measure the spread or variability of a data set. Whether you're a student analyzing exam scores, a business professional evaluating sales data, or a researcher interpreting experimental results, knowing how to calculate standard deviation in Excel can provide valuable insigh
11 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg