Python Algorithms

Quick Sort in Python

Quicksort partitions values around a pivot, then recursively sorts values smaller than and greater than the pivot.

What is Quick Sort?

Quicksort partitions values around a pivot, then recursively sorts values smaller than and greater than the pivot.

Learn quicksort with a concise recursive Python implementation.

When should you use it?

  • Practice problem solving and data structures.
  • Process data when every algorithm step must be explicit.
  • Prepare for programming exercises, exams, and interviews.

Quick Sort in Python visualizer

O(n log n)

Use Play or Step to follow each comparison and data movement.

Example code

Run code →
main.py
def quick_sort(values):
    if len(values) <= 1:
        return values
    pivot = values[len(values) // 2]
    lower = [value for value in values if value < pivot]
    equal = [value for value in values if value == pivot]
    higher = [value for value in values if value > pivot]
    return quick_sort(lower) + equal + quick_sort(higher)

print(quick_sort([10, 7, 8, 9, 1, 5]))

Expected output

[1, 5, 7, 8, 9, 10]

How it works

This readable version creates three partitions. Average time complexity is O(n log n), although poor pivot choices can produce O(n²).

Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.

Practice exercises

Modify the runnable example with the exercises below to build understanding beyond copying the result.

  1. Try empty, single-item, and duplicate-value inputs.
  2. Print state after every step to observe the algorithm.
  3. Benchmark 100, 1,000, and 10,000 items, then compare another approach.
Run in Python IDE →