Week 3
Week 3
QUICK SORT
No need to merge!
Input list
Identify pivot
Mark lower elements and upper elements
Rearrange the elements as lower-pivot-upper
Partitioning
Summary
Can build the lower and upper segments from opposite ends and meet in the middle
Need to analyze the complexity of quicksort
Analysis
T(n) = 2T(n/2) + n
T(n) is O(nlogn)
Randomizaton
Any fixed choice of pivot allows us to construct worst case input
Instead, choose pivot position randomly at each step
Expected run time is again O(nlogn)
Iterative quicksort
Quicksort in practice
Summary
Good example of a situation when the worst case upper bound is pessimistic
Stable Sorting
Do not allow elements from the right to overtake elements on the left
While merging, prefer the left list while breaking ties
Other criteria
Database tables taht are too large to store in memory all at once
Retrieve in parts from the disk and write back
Other O(nlogn) algorithms exist - heapsort
Sometimes hybrid strategies are used
Sequences
Lists
Arrays
Lists
Flexible length
Easy to modify the structure
Values are scattered in memory
Arrays
Fixed size
Allocate a contigous block of memory
Supports random access
Lists
Typically a sequence of nodes
Each node contains a value and points to the next node in the sequence
"Linked" list
Easy to modify
Arrays
"Random" access
Operations
Summary
Empty list?
self.value is None
Creating lists
class Node:
def __init__(self, v = None):
self.value = v
self.next = None
return
def isempty(self):
if self.value == None:
return True
else:
return False
Appending to a list
Iterative implementation
temp = self
while temp.next != None:
temp = temp.next
temp.next = Node(v)
return
newnode = Node(v)
# Switch links
(self.next, newnode.next) = (newnode, self.next)
return
Delete a value v
Summary
Lists in Python
zerolist = [0,0,0]
zeromatrix = [zerolist, zerolist, zerolist]
zeromatrix[1][1] = 1
print(zeromatrix)
Numpy Arrays
import numpy as np
zeromatrix = np.zeros(shape = (3,3))
newarray = np.array([[0,1],[1,0]])
row2 = np.arange(5)
C = 3*A + B
C = np.matmul(A,B)
same as C[i,j] = A[i.k].B[k,j]
Very useful for data science
Summary
Dictionary
Implementing a dictionary
Hash Table
Summary