šŸ“Š Sorting

Putting things in order — slow ways and clever ways

← Back to Algorithms

🫧 Bubble sort — simple but slow

Bubble sort repeatedly walks the list, swapping neighbors that are out of order. Big values "bubble up" to the end. Easy to understand, but O(n²) — slow for big lists.

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

šŸ” The Python swap trick

a, b = b, a swaps two values in one clean line — no temporary variable needed!

šŸŽÆ Selection sort — find the smallest

Selection sort finds the smallest item and puts it first, then the next smallest, and so on. Also O(n²), but it makes fewer swaps.

def selection_sort(items): n = len(items) for i in range(n): smallest = i for j in range(i + 1, n): if items[j] < items[smallest]: smallest = j items[i], items[smallest] = items[smallest], items[i] return items

⚔ Merge sort — divide and conquer

Merge sort splits the list in half, sorts each half (recursively!), then merges the two sorted halves together. Much faster: O(n log n).

def merge_sort(items): if len(items) <= 1: # base case return items mid = len(items) // 2 left = merge_sort(items[:mid]) right = merge_sort(items[mid:]) return merge(left, right) def merge(left, right): result = [] i = j = 0 while i < len(left) and j < len(right): if left[i] <= right[j]: result.append(left[i]); i += 1 else: result.append(right[j]); j += 1 result.extend(left[i:]) result.extend(right[j:]) return result

šŸ“ Comparing the sorts

AlgorithmBig-OIdea
Bubble sortO(n²)Swap neighbors
Selection sortO(n²)Pick the smallest
Merge sortO(n log n)Split & merge
Python's .sort()O(n log n)Timsort (built-in)

šŸ’” In real life

You rarely write your own sort — Python's sorted() and .sort() are highly optimized. But understanding how sorting works makes you a better problem-solver.

āœ… What you learned

  • Bubble & selection sort are simple but O(n²).
  • Merge sort uses divide and conquer for O(n log n).
  • Swap values with a, b = b, a.
  • Real code uses Python's built-in sorted().