Sorting Algorithms

selection sort

Step-by-step example with [3, 1, 2]:

Step i min_idx Array before swap Array after swap
0 0 1 [3, 1, 2] [1, 3, 2]
1 1 2 [1, 3, 2] [1, 2, 3]
2 2 2 [1, 2, 3] [1, 2, 3]

Detailed steps:

  1. i = 0: min_idx = 1 (1 is smallest), swap arr[0] and arr[1] → [1, 3, 2]
  2. i = 1: min_idx = 2 (2 is smallest in [3,2]), swap arr[1] and arr[2] → [1, 2, 3]
  3. i = 2: already sorted

Insertion sort

Step-by-step example with [3, 1, 2]:

Step i key Array after shifts Array after insert
0 - - [3, 1, 2] [3, 1, 2]
1 1 1 [3, 3, 2] [1, 3, 2]
2 2 2 [1, 3, 3] [1, 2, 3]

Detailed steps:

  1. Initial: [3, 1, 2]
  2. i = 1, key = 1:
    • Compare 1 < 3 → shift 3 right → [3, 3, 2]
    • Insert 1 at position 0 → [1, 3, 2]
  3. i = 2, key = 2:
    • Compare 2 < 3 → shift 3 right → [1, 3, 3]
    • Compare 2 > 1 → stop
    • Insert 2 at position 1 → [1, 2, 3]
  4. Done: [1, 2, 3]

Merge Sort

Step-by-step example with [3, 1, 2]:

  1. Split: [3, 1, 2] → [3] and [1, 2]
  2. [1, 2] splits to [1] and [2]
  3. Merge [1] and [2] → [1, 2]
  4. Merge [3] and [1, 2]:
    • Compare 3 and 1 → 1 goes first
    • Compare 3 and 2 → 2 goes next
    • 3 is left, goes last
    • Result: [1, 2, 3]

Quick sort

Step-by-step example with [3, 1, 2]:

  1. Array: [3, 1, 2], pivot = 1 (middle element)
    • left: []
    • middle: [1]
    • right: [3, 2]
  2. Recursively sort right: [3, 2], pivot = 2
    • left: []
    • middle: [2]
    • right: [3]
  3. Combine: [] + [2] + [3] = [2, 3]
  4. Combine all: [] + [1] + [2, 3] = [1, 2, 3]

bubble sort

Step-by-step example with [3, 1, 2]:

Pass j comparisons Array after swaps
1 (3>1) swap, (3>2) swap [1, 2, 3]
2 (1>2) no swap [1, 2, 3]

Detailed steps:

  1. First pass:
    • Compare 3 > 1 → swap → [1, 3, 2]
    • Compare 3 > 2 → swap → [1, 2, 3]
  2. Second pass:
    • Compare 1 > 2 → no swap
  3. Array is sorted: [1, 2, 3]

Original Source