






Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!







4/9/
Goal : Given unsorted list b, search range h..k-1 for k >=h and h and k valid indices for b, and target value v, return index n of v's first occurrence in b[h..k-1] (-1 if not found) Restated as postcondition : if n=-1, then v is not in b[h..k-1]. Otherwise, v = b[n] and v is not in b[h..n-1]. Idea : keep an index i, marking position of next thing unchecked; everything to its left has been verified to not be v. If i < k and b[i] = v, return i as n; if i==k, v isn't in b. v not here? h i k inv : b 4/9/
Goal : Given sorted list b, search range h..k for k >=h and h and k valid indices for b, and target value v, return index n of v's first occurrence in b[h.. k ] (-1 if not found) Restated as postcondition : if n=-1, then v is not in b[h.. k ]. Otherwise, v = b[n] and v is not in b[h..n-1]. Idea : keep indices i and j, marking position of next thing not known to be < v, and the first thing known to be >=v. Check halfway btwn 'em. If i <= k and b[i] = v, return i as n; if i> k or i ==j and b[i] not v or i=k+1, v isn't in b. =v h i j k inv : b 4/9/
=v h i j k inv : b def bin_search(b,h,k,v): # omitting the last return for space """(see previous)""" Q1: (A) i = h; j=k (B) i=h-1; j = k+1 (C) i = h-1; j = k (D) i = h; j = k+
while Q2: (A) i==j (B) i < j (C) i <=j if b[i] == v: return i mid = (i+j)/ if b[mid] < v: Q3: (A) i = mid (B) i = mid+ else: j = mid # may skip vast section of b 4/9/
? 0 n pre: b (^) sorted 0 n post: b sorted 0 i n inv: b (^)?
while ...:
j = i + b[i:n] .index(min(b[i:n])) sorted, ≤ b[i..] 0 i n inv: b (^) ≥ b[0..i-1] or? if i = 0
2 4 4 6 6 8 9 9 7 8 9 i n 2 4 4 6 6 7 9 9 8 8 9 i n 2 4 4 6 6 7 9 9 8 8 9 i n Note the swap of the reds 4/9/
sorted, ≤ b[i..] 0 i n inv: b (^) ≥ b[0..i-1] or? if i = 0
4/9/
def dnf(b, h, k): """(DNF explanation omitted for space.) Returns: split-points as a tuple (i,j)"""
# inv: b[h..t-1] < 0, b[t..i-1] ?, b[i..j] = 0, b[j+1..k] > 0 while t < i: if b[i-1] < 0:
elif b[i-1] == 0:
else:
return4/9/13 (i, j)
def dnf(b, h, k): """Returns: partition points as a tuple (i,j)""" t = h; i = k+1, j = k;
while t < i: if b[i-1] < 0: b[i-1], b[t] = b[t], b[i-1] t = t+ elif b[i-1] == 0: i = i- else: b[-1], b[j] = b[j], b[i- i = i-1; j = j-
return (i, j) -1 -2 3 -1 0 0 0 6 3 h t i j k -1 -2 3 -1 0 0 0 6 3 h t i j k < 0? = 0 > 0 -1 -2 -1 3 0 0 0 6 3 h t i j k -1 -2 -1 0 0 0 3 6 3 h t j k 4/9/