def selection_sort(A):
n = len(A)
for i in range(n):
min_index = i
for j in range(i + 1, n):
if A[j] < A[min_index]:
min_index = j
# Swap the found minimum element with the first element
A[i], A[min_index] = A[min_index], A[i]
return A
def bubble_sort(A):
n = len(A)
for i in range(n):
for j in range(n - 1, i, -1):
if A[j - 1] > A[j]:
# Swap adjacent elements
A[j - 1], A[j] = A[j], A[j - 1]
return A
# | Design Strategy | Description | Pros/Cons | Examples |
---|---|---|---|---|
1. | Brute Force | - Directly based on the problem statement. | ✅ Straightforward ❌ May vary between individuals due to subjectivity. |
Selection Sort, Bubble Sort |
2. | Decrease and Conquer | - Decrease the problem size ($n$) to size $n-1$. | ✅: Systematic approach to problem-solving. ✅: Facilitates recursive thinking. |
|
2.1 | TOP-DOWN | - Do upfront work to nibble away one (or few) element(s): $n \rightarrow n-1$
MAIN IDEA: 1. I pretend to be a Lazy Manager. 2. I nibble away at the problem to make it smaller. 3. I do upfront work of adding the nibble to the solution. 4. I hand over my solution and the remaining problem to my subordinate. (They do the same.) CODING TIP: Write code from the perspective of an arbitrary lazy manager to sort the array: ..BEFORE: The managers above me would have ensured that all previous elements are sorted. (because they are lazy managers too!) ..MY JOB: I just extend the sorted region by one more element. ..AFTER: I hand over the remaining work to my subordinate. (They do the same.) |
Selection Sort, Bubble Sort | |
2.2 | BOTTOM-UP | - Work at the end to extend the $(n-1)^{st}$ solution: $n-1 \rightarrow n$
MAIN IDEA: 1. I pretend to be a Lazy Manager. 2. I nibble away at the problem to make it smaller. I keep the nibble for work to be done later. 3. I hand over the remaining problem to my subordinate. (They do the same.) 4. The subordinate returns their solution to me. 5. I do the (later) work of adding my nibble to the solution. 6. I hand over my solution to my manager. |
Insertion Sort |
key
).key
with elements in the sorted subarray.key
one position to the right.key
at the correct position.[2, 4, 5, 6, 7, 8, 3]
3
:
3
with 8
, 7
, 6
, 5
, 4
, shifting each to the right.2
is less than 3
.3
after 2
.