Am_lect_24 - Binary Search Consider an array a1 a2 an of numbers sorted in increasing order and suppose we want to know if a particular number b

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 DocumentRight 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
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.

This note was uploaded on 12/24/2010 for the course CS CS 173 taught by Professor Fleck during the Spring '10 term at University of Illinois, Urbana Champaign.

Page1 / 4

Am_lect_24 - Binary Search Consider an array a1 a2 an of numbers sorted in increasing order and suppose we want to know if a particular number b

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online