Introduction
Imagine you have a messy pile of books and want to arrange them from shortest to tallest. Sorting algorithms help computers organize data in a specific order, making it easier to find or use later.
Jump into concepts and practice - no test required
Imagine lining up students by height. Bubble sort is like students comparing heights with their neighbor and swapping places if needed, passing through the line many times. Selection sort is like picking the shortest student from the group and placing them at the front one by one.
Unsorted List: 5 3 8 4 2 Bubble Sort Passes: Pass 1: 3 5 4 2 8 Pass 2: 3 4 2 5 8 Pass 3: 3 2 4 5 8 Pass 4: 2 3 4 5 8 Selection Sort Steps: Step 1: Find min (2), swap with first (5) → 2 3 8 4 5 Step 2: Find min (3), already in place → 2 3 8 4 5 Step 3: Find min (4), swap with third (8) → 2 3 4 8 5 Step 4: Find min (5), swap with fourth (8) → 2 3 4 5 8 Step 5: Last item sorted → 2 3 4 5 8
arr in Python?for i in range(len(arr)): correctly loops over indices; others are incorrect or off-by-one.[4, 2, 5, 1]?Initial list: [4, 2, 5, 1] Pass 1: Compare and swap neighbors if needed
arr = [3, 1, 4]
for i in range(len(arr)):
min_idx = i
for j in range(i+1, len(arr)):
if arr[j] < arr[min_idx]:
min_idx = j
arr[i], arr[min_idx] = arr[min_idx], arr[i]
print(arr)[7, 3, 5, 2, 9]. After two full passes of selection sort, what will the list look like?