6.006 Course Notes
Wanlin Li
Fall 2018
1 September 6
• Computation
• Definition. Problem: matching inputs to correct outputs
• Definition. Algorithm: procedure/function matching each input to single out- put, correct if matches problem
• Want program to be able to handle infinite space of inputs, arbitrarily large size of input
• Want finite and efficient program, need recursive code
• Efficiency determined by asymptotic growth Θ()
• O(f(n)) is all functions below order of growth of f(n)
• Ω(f(n)) is all functions above order of growth of f(n)
• Θ(f(n)) is tight bound
• Definition. Log-linear: Θ(n log n)
Θ(nc) • Definition. Exponential: b
• Algorithm generally considered efficient if runs in polynomial time
• Model of computation: computer has memory (RAM - random access memory) and CPU for performing computation; what operations are allowed in constant time
• CPU has registers to access and process memory address, needs log n bits to handle size n input
• Memory chunked into “words” of size at least log n
1 6.006 Wanlin Li
32 10 • E.g. 32 bit machine can handle 2 ∼ 4 GB, 64 bit machine can handle 10 GB
• Model of computaiton in word-RAM
• Ways to solve algorithms problem: design new algorithm or reduce to already known algorithm (particularly search in data structure, sort, shortest path)
• Classification of algorithms based on graph on function calls
• Class examples and design paradigms: brute force (completely disconnected), decrease and conquer (path), divide and conquer (tree with branches), dynamic programming (directed acyclic graph), greedy (choose which paths on directed acyclic graph to take)
• Computation doesn’t have to be a tree, just has to be directed acyclic graph
2 September 11
• Example. Check if array contains item
1 def contains(A,v): 2 fori in range(len(A)): 3 if A[i] == v: 4 return True 5 return False
• Other option to call function recursively using additional parameter, decrease and conquer; contains(A, v, i = 0)
• Divide and conquer would check if middle element is desired element, otherwise return if element is in either half of array; still O(n)
• Maximum subarray sum problem: what is the largest sum of any nonempty (contiguous) subarray?
• Example. Brute force
1 def MSS(A): 2 m = A[0] 3 forj in range(1,len(A)+1): 4 fori in range(0,j): 5 m = max(m, SS(A,i,j)) 6 returnm
where SS is helper function for summing subarray; O(n3) because there are O(n2) nodes and each requires linear time
• Divide and conquer approach: MSS fully in left half of array, fully in right half of array, or contains middle two elements
2 6.006 Wanlin Li
1 def MSS(A, i=0, j=None): 2 ifj is None: 3 j = len(A) 4 if j-i == 1: 5 return A[i] 6 c = (i+j)//2 7 return max(MSS(A,i,c), MSS(A,c,j), MSS_EA(A,i,c) + MSS_SA(A,c,j)) 8 def MSS_SA(A,i,j): 9 s = m = A[i] 10 fork in range(1, j-i): 11 s += A[i+k] 12 m = max(s,m) 13 returnm 14 def MSS_EA(A,i,j): 15 s = m = A[j-1] 16 fork in range(1,j-i): 17 s += A[j-1-k] 18 m = max(s,m) 19 returnm