Example Algorithms

Selection Sort

Python 3.6
1def selection_sort(L):
2    for i in range(len(L)):
3        idx_min = i
4        for j in range(i, len(L)):
5            if L[j] < L[i]:
6                idx_min = j
7        L[idx_min], L[i] = L[i], L[idx_min]
8
9nums = [2, 4, 3, 1]
10selection_sort(nums)
11print(nums)
line that has just executed

next line to execute

Print output (drag lower right corner to resize)
Frames
Objects

Binary Search

Python 3.6
1# assume L is already sorted
2def binary_search(L, target):
3    left_idx = 0 # inclusive
4    right_idx = len(L) # exclusive
5
6    # keep splitting our list in half, until
7    # it's length is <= 1
8    while right_idx - left_idx > 1:
9        mid_idx = (right_idx + left_idx) // 2
10        mid = L[mid_idx]
11
12        # throw away left or right half?
13        if target >= mid:
14            left_idx = mid_idx
15        else:
16            right_idx = mid_idx
17
18    # did we cut down to a list of length 1 containing target?
19    return right_idx > left_idx and L[left_idx] == target
20
21L = [1, 2, 9, 42, 60, 70, 80, 99]
22found = binary_search(L, 80)
23print(found)
line that has just executed

next line to execute

Print output (drag lower right corner to resize)
Frames
Objects

Merge Sort

Python 3.6
1def merge(L1, L2):
2  rv = []
3  idx1 = 0
4  idx2 = 0
5
6  while True:
7    done1 = idx1 == len(L1)
8    done2 = idx2 == len(L2)
9
10    if done1 and done2:
11      return rv
12
13    choose1 = False
14    if done2:
15      choose1 = True
16    elif not done1 and L1[idx1] < L2[idx2]:
17      choose1 = True
18
19    if choose1:
20      rv.append(L1[idx1])
21      idx1 += 1
22    else:
23      rv.append(L2[idx2])
24      idx2 += 1
25
26  return rv
27
28def merge_sort(L):
29  if len(L) < 2:
30    return L
31  mid = len(L) // 2
32  left = L[:mid]
33  right = L[mid:]
34  left = merge_sort(left)
35  right = merge_sort(right)
36  return merge(left, right)
37
38result = merge_sort([4, 1, 2, 3])
39print(result)
line that has just executed

next line to execute

Print output (drag lower right corner to resize)
Frames
Objects