cse 2050 exam 2
[9, 7, 4, 2, 1]
[1, 7, 4, 2, 9]
[1, 2, 4, 7, 9] - ANS-selection sort -
[9, 7, 4, 2, 1]
[1, 9, 7, 4, 2]
[1, 7, 4, 2, 9]
[1, 2, 7, 4, 9]
[1, 2, 4, 7, 9] - ANS-cocktail sort (bubble with alternating directions)
[9, 7, 4, 2, 1]
[7, 4, 2, 1, 9]
[4, 2, 1, 7, 9]
[2, 1, 4, 7, 9]
[1, 2, 4, 7, 9] - ANS-bubble sort - after x calls, the last x items are sorted
[9, 7, 4, 2, 1]
[7, 9, 4, 2, 1]
[4, 7, 6, 2, 1]
[2, 4, 7, 9, 1]
[1, 2, 4, 7, 9] - ANS-insertion sort - with each inner loop, select the next highest item and
move it to the end
binary search - ANS-a search algorithm that starts at the middle of a sorted set of
numbers and removes half of the data; this process repeats until the desired value is
found or all elements have been eliminated.
binary search - running time - ANS-asymptotic running time is o(log n)
binary search running time - ANS-linear time if we used slicing; asymptotic running time
is O(logn) because the tree of function calls a single chain of length at most O(log n) -
number of times you can cut n in half before it gets down to 1
bubble sort - algorithm - ANS-def --sort(L):
has_swapped = True
while(has_swapped):
has_swapped = False
, for i in range(len(L)-1):
if L[i] > L[i+1]:
L[i], L[i+1] = L[i+1], L[i]
swaps += 1
has_swapped = True
if no elements swapped during the pass, can safely exit
bubble sort - best, worst, average - ANS-O(n), O(n^2), O(n^2)
dynamic programming - ANS-storing previously calculated values to prevent repetitive
calculations and allow for quick retrievals as well as using smaller values to solve for
even larger ones
example binary search algorithm - ANS-def bs(array, element, start, end):
if start > end:
return -1
mid = (start + end) // 2
if element == array[mid]:
return mid
if element < array[mid]:
return bs(array, element, start, mid-1)
else:
return bs(array, element, mid+1, end)
example recursive program using memoization - ANS-def fib(n, fib_cache):
if n in fib_cache:
return fib_cache[n]
fib_cache[n] = fib(n-1, fib_cache) + fib(n-2, fib_cache)
return fib_cache[n]
fib_cache = {0:1, 1:1}
example recursive program using tabulation - ANS-def Fibonacci(n):
f=[]
f.append(1)
f.append(1)
for i in range(2, n+1):
f.append(f[i-1] + f[i-2])
return f[n]