Lecture 13:�Problem Solving (Sorting)
Announcement
2
Homework 1
def selection_sort(list):
for i in range(len(list)):
smallest = i
for j in range(i+1, len(list)):
if list[j] < list[smallest]:
smallest = j
list[i], list[smallest] = list[smallest], list[i]
Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
Value | -7 | -4 | -1 | 6 | 10 | 5 | 4 | 2 | 15 | 21 |
Sorted
i
smallest
swap
Q. Can you implement this with selection sort with recursion?
3
Homework 1 – Solution
Def SelectionSort(A[], i): # i = last index of the sorted region
Time complexity : O(n^2)
4
Homework 2
def merge_sort(list):
if len(list) > 1:
mid = len(list) // 2
left = list[:mid]
right = list[mid:]
merge_sort(left)
merge_sort(right)
# TODO(students): merge left & right in the list
“else” for this is the base case, where the recursive calls are done.
We skip it here, since there’s no action item in the base case.
Q. Please implement merge sort. (# TODO section below)
5
Homework 2 – Solution
6
Homework 3
7
Homework 3 – Solution
8
Homework 4
9
Homework 4 – Solution
nums = [3, 30, 34, 5]���
Time complexity : O(nlog(n))
10
Homework 5
11
Homework 5 – Solution
12