Basic python 2
Basic python 2
2
DIVIDE AND CONQUER ASTU
3
ASTU
4
ASTU
Sequential Search
5
ASTU
6
ASTU
What if L is sorted?
7
BINARY SEARCH ASTU
Basic idea
Assumption: the list L is sorted.
L = [1, 2, 6, 8, 11, 17, 23]
q = 19
low = 0 3 high= 6
1 2 6 8 11 17
23
mid = (low + high) / 2
L[mid] = 8
With a single comparison, we can reduce the search
space by half. Divide and conquer!
8
ASTU
Observations
1. When low == high, one additional compari-
son is required to make the final decision. At this
time, the length of the sub-list is reduced to one.
base case
10
ASTU
11
ASTU
if low == high:
return L[low] == q Base case
Basic Idea
13
ASTU
14
ASTU
def merge_sort(L):
if len(L) < 2:
base case
return L[:]
mid = len(L) / 2
left = merge_sort(L[:mid ]) recursive case
right = merge_sort(L[mid:])
return merge(left, right)
At most n comparisons.
16
ASTU
def merge_sort(L):
if len(L) < 2:
return L[:]
mid = len(L) / 2
left = merge_sort(L[:mid])
right = merge_sort(L[mid:])How many comparisons?
return merge(left, right)
19
ASTU
O(n )
20
ASTU
21
ASTU