{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

am_lect_24 - Binary Search Consider an array a1 a2 an of...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
Binary Search Consider an array a 1 , a 2 , …, a n of numbers sorted in increasing order , and suppose we want to know if a particular number b appears in the array. The following algorithm returns True if b appears, and returns False otherwise. 1: BinarySearch(a 1 , a 2 , ..., a n : array of reals, b : real) 2: lo := 1; hi := n 3: while lo <= hi 4: mid := (lo + hi)/2 5: if a mid = b then return True 6: else if a mid < b then lo := mid + 1 7: else hi := mid – 1 8: end while 9: return False Explanation : Look at the mid-point and if a mid = b (line 5) then we return True . Otherwise, if a mid < b (line 6) then look in the range a mid+1 , …, a n and if a mid > b (line 7) then look in the range a 1 , …, a mid 1
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
Running time analysis of Binary Search Clearly the time before and after the loop is O (1), and the loop body takes O (1) time per iteration. Question: How many loop iterations are there? Clearly, this depends on the gap between “hi” and “lo”. We can write a recurrence for the number of loop iterations L ( n
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}