Skip to content

Sorting Algorithms in Python

--8<: "core-logic/sorting-algorithms.md"

1. Bubble Sort

def bubble_sort(arr):
    n = len(arr)
    for i in range(n):
        for j in range(0, n-i-1):
            if arr[j] > arr[j+1]:
                arr[j], arr[j+1] = arr[j+1], arr[j] # Swap
    return arr

print(bubble_sort([64, 34, 25, 12, 22]))

2. Quick Sort (Recursive)

def quick_sort(arr):
    if len(arr) <= 1:
        return arr
    pivot = arr[len(arr) // 2]
    left = [x for x in arr if x < pivot]
    middle = [x for x in arr if x == pivot]
    right = [x for x in arr if x > pivot]
    return quick_sort(left) + middle + quick_sort(right)

print(quick_sort([64, 34, 25, 12, 22]))

Python's Built-in Sort: Timsort

In real-world Python development, we rarely write our own sorting algorithms. Python uses a highly optimized algorithm called Timsort (a hybrid of Merge Sort and Insertion Sort).

# Modifies the original list
mylist = [5, 2, 9, 1]
mylist.sort()

# Returns a new sorted list
newlist = sorted([5, 2, 9, 1])

Industry Fact

Python's sort() and sorted() are written in C and are extremely fast. Always use them unless you are explicitly asked to implement a specific algorithm for an exam or interview.