Back to Arrays & Sorting

Quick Sort

Quick Sort is a highly efficient, Divide-and-Conquer sorting algorithm. It selects a pivot element from the array and partitions the other elements into two sub-arrays according to whether they are less than or greater than the pivot.

The Partitioning Mechanism:

Python Implementation (Lomuto Partition)

def quick_sort(arr, low, high):
    if low < high:
        # pi is partitioning index, arr[pi] is now at right place
        pi = partition(arr, low, high)

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

def partition(arr, low, high):
    pivot = arr[high]  # Pivot choice
    i = low - 1  # Index of smaller element

    for j in range(low, high):
        if arr[j] < pivot:
            i += 1
            arr[i], arr[j] = arr[j], arr[i]

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

Complexity Analysis