Description

Quick Sort is a Sorting Algorithm that uses Recursion and Divide and Conquer to sort an array.
?

Reach for when

You want a fast, general-purpose comparison sort — O(n log n) average, and the classic version sorts in place. Trade-offs: unstable, and O(n²) worst case on a bad pivot (randomize the pivot). Prefer merge sort if you need stability or a guaranteed O(n log n).

Runtime

O(n log n) on average, but can be as bad as O(n^2) in the worst case. The runtime depends on the input data and how the pivot is chosen.

Visualization

Pasted image 20250222102936.png

Pseudocode

Check if the array is of length 1 or 0 if it is do nothing
Pick a pivot point (you can pick anything)
Take everything that is larger then that and preform quick sort
Take everything that is smaller then that and preform quick sort 
return the result of the smallest, pivot, and largest sorts

Code

def quick_sort(arr):
    if len(arr) < 2:
        return arr

    pivot = arr[0]
    smaller = [v for v in arr[1:] if v <= pivot]
    larger = [v for v in arr[1:] if v > pivot]
    return quick_sort(smaller) + [pivot] + quick_sort(larger)