Search Algorithms

Searching algorithms:

Amortized cost

Why may one bother sorting first?

Sort Algorithms

Monkey sort

def bogo_sort(L):
  while not is_sorted(L):
    random.shuffle(L)

Bubble sort

Bubble sort animation In this animation, we assume that the first n integers are present in the list in a random order. As the passes of bubble sort proceed, the largest elements start identifying their correct position, e.g., the integer of value n is at the nth index.

Code:

def bubble_sort(L):
  swap = False
  while not swap:  # O(len(L))
    swap = True
    for j in range(1, len(L)):  # O(len(L))
      if L[j-1] > L[j]:
        swap = False
        temp = L[j]
        L[j] = L[j-1]
        L[j-1] = temp

Selection sort

Analyzing slection sort

Complexity of selection sort

def selection_sort(L):
  suffixSt = 0
  while suffixSt != len(L):     # executed len(L) times
    for i in range(suffixSt, len(L)):   #executed len(L) - suffixSt times
      if L[i] < L[suffixSt]:
        L[suffixSt], L[i] = L[i], L[suffixSt]
    suffixSt += 1

Merge sort

Use a divide-and-conquer approach:

Idea:

Example of merging:
Left in list 1 Left in list 2 Compare Result
[1,5,12,18,19,20] [2,3,4,17] 1, 2 []
[5,12,18,19,20][2,3,4,17]5, 2[1]
[5,12,18,19,20][3,4,17]5,3[1,2]
[5,12,18,19,20][4,17]5,4[1,2,3]
[5,12,18,19,20][17]5,17[1,2,3,4]
[12,18,19,20][17]12,17[1,2,3,4,5]
[18,19,20][17]18,17[1,2,3,4,5,12]
[18,19,20][]18,--[1,2,3,4,5,12,17]
[][]18,--[1,2,3,4,5,12,17,18,19,20]

Merging sublists step

def merge(left, right):
  result = []
  i, j = 0, 0
  while i < len(left) and j < len(right):
    #left and right sublists are ordered.
    #move indices for sublists depending on which sublist holds next smallest element
    if left[i] < right[i]:
      result.append(left[i])
      i += 1
    else:
      result.append(right[j])
      j += 1
  while i < len(left):
    #when right sublist is empty
    result.append(left[i])
    i += 1
  while j < len(right):
    #when left sublist is empty
    result.append(right[j])
    j += 1
  return result

Complexity of merging sublists step

Mergesort algorithm recursive

def merge_sort(L):
  if len(L) < 2:
    return L[:]   #base case
  else:
    middle = len(L)//2
    left = merge_sort(L[:middle])  #divide; first half
    right = merge_sort(L[middle:]) #divide; second half
    return merge(left, right)
Mergesort example

Complexity of mergesort

Sorting summary: