Lecture Notes on 23 Sep 2020 * Sequential Search Efficiency: O(n) Input: a is a list and x is an element to be found Output: the index of the first occurence of x or -1 if x is not in the list def sequential_search (a, x): for i in range (len(a)): if (a[i] == x): return i return -1 * Binary Search Efficiency: O(log n), log base 2 Pre-condition: list a is sorted in ascending order Input: a is a list and x is an element to be found Output: the index of the first occurence of x or -1 if x is not in the list def binary_search (a, x): lo = 0 hi = len(a) - 1 while (lo <= hi): mid = (lo + hi) // 2 if (x > a[mid]): lo = mid + 1 elif (x < a[mid]): hi = mid - 1 else: return mid return -1 * Selection Sort Efficiency: O(n^2) Input: a is a list Output: function does not return anything but a is sorted in place def selection_sort (a): for i in range (len(a) - 1): # find the minimum min_val = a[i] min_idx = i for j in range (i + 1, len(a)): if (a[j] < min_val): min_val = a[j] min_idx = j # Swap the minimum element with the element at the ith place a[min_idx] = a[i] a[i] = min_val * Merging Efficiency: O(n) Pre-condition: a and b are sorted lists in ascending order Input: a and b are sorted lists Output: returns c that is the merged list in ascending order def merge (a, b): c = [] idxA = 0 idxB = 0 while ((idxA < len(a)) and (idxB < len(b))): if (a[idxA] < b[idxB]): c.append (a[idxA]) idxA = idxA + 1 else: c.append (b[idxB]) idxB = idxB + 1 # if a is not empty write out the remaining elements while (idxA < len(a)): c.append (a[idxA]) idxA = idxA + 1 # if b is not empty write out the remaining elements while (idxB < len(b)): c.append (b[idxB]) idxB = idxB + 1 return c