Show understanding of insertion sort and bubble sort methods
19.1 Algorithms – Sorting Basics 📚
Insertion Sort – Like Sorting Playing Cards
Insertion sort builds the final sorted array one item at a time. Imagine you’re sorting a hand of playing cards: you pick up each card and insert it into its correct position among the cards already sorted. The algorithm is simple, stable, and great for small or nearly sorted lists.
- Start with the second element (index 1) as the “current” item.
- Compare it with the elements to its left.
- Shift larger elements one position to the right.
- Insert the current item into the vacated spot.
- Move to the next element and repeat until the list is sorted.
Pseudocode:
for i = 1 to n-1 do
key = A[i]
j = i - 1
while j >= 0 and A[j] > key do
A[j+1] = A[j]
j = j - 1
end while
A[j+1] = key
end for
Example: Sort the array [8, 3, 5, 4, 6] step‑by‑step.
| Iteration | Array State |
|---|---|
| Start | [8, 3, 5, 4, 6] |
| Insert 3 | [3, 8, 5, 4, 6] |
| Insert 5 | [3, 5, 8, 4, 6] |
| Insert 4 | [3, 4, 5, 8, 6] |
| Insert 6 | [3, 4, 5, 6, 8] |
Complexity: $O(n^2)$ in the worst case, $O(n)$ best case (already sorted). Space complexity is $O(1)$; it’s an in‑place algorithm. It’s stable – equal elements keep their relative order.
Bubble Sort – Like Bubbles Rising to the Surface
Bubble sort repeatedly steps through the list, compares adjacent items, and swaps them if they’re in the wrong order. Think of a pot of hot chocolate: the biggest “bubbles” (largest numbers) rise to the top after each pass. It’s easy to understand but not very efficient for large lists.
- Start at the beginning of the array.
- Compare each pair of adjacent items.
- Swap if the left item is greater than the right.
- After one full pass, the largest item “bubbles” to the end.
- Repeat the process for the remaining unsorted portion.
Pseudocode:
for i = 0 to n-2 do
for j = 0 to n-2-i do
if A[j] > A[j+1] then
swap A[j] and A[j+1]
end if
end for
end for
Example: Sort the array [4, 1, 3, 2] step‑by‑step.
| Pass | Array State |
|---|---|
| Start | [4, 1, 3, 2] |
| After 1st inner loop | [1, 4, 3, 2] |
| After 2nd inner loop | [1, 3, 4, 2] |
| After 3rd inner loop | [1, 3, 2, 4] |
| Second pass | [1, 2, 3, 4] |
Complexity: $O(n^2)$ in all cases. Space complexity is $O(1)$; it’s an in‑place algorithm. Bubble sort is also stable.
Key Takeaway: Both insertion sort and bubble sort are simple to implement and understand, but they’re best suited for small or nearly sorted datasets. For larger data, more efficient algorithms like quicksort or mergesort are preferred. 🚀
Revision
Log in to practice.