binsearch - CSE 241 Algorithms and Data Structures...

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

View Full Document Right Arrow Icon

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

View Full DocumentRight Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: CSE 241 Algorithms and Data Structures 9/16/2008 Binary Search Algorithm This handout gives pseudocode for the Θ(log n ) binary search algorithm. As an exercise, think about how you would implement this algorithm without making any recursive calls. Input : a sorted array A [ p . . . r ], defined for indices between p and r . Also, a number x . Returns : the index of x in A if it is present; otherwise, the special value notFound . If x appears several times in A , one of its indices is returned. 1 Bsearch ( x , A , p , r ) // base case if ( p = r ) { if ( A [ p ] = x ) return p else return notFound } mid ← d ( p + r ) / 2 e if ( A [mid] > x ) return Bsearch ( x , A , p , mid- 1) else return Bsearch ( x , A , mid, r ) 2 1 Correctness To see correctness, start with an invariant : at the beginning of each call to the Bsearch function, if the value x occurs in A , it lies in A [ p..r ] . The invariant is an important property of the algorithm that holds at all times while it is running. As we’ll see, the invariant is useful in understandingthat holds at all times while it is running....
View Full Document

This note was uploaded on 03/03/2010 for the course CSE 241 taught by Professor Cse241 during the Spring '08 term at Washington University in St. Louis.

Page1 / 3

binsearch - CSE 241 Algorithms and Data Structures...

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