binsearch - CSE 241 Algorithms and Data Structures Binary...

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

View Full Document Right Arrow Icon
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
Image of page 1

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

View Full Document Right Arrow Icon
Bsearch ( x , A , p , r ) // base case if ( p = r ) { if ( A [ p ] = x ) return p else return notFound } mid ( p + r ) / 2 if ( A [mid] > x ) return Bsearch ( x , A , p , mid - 1) else return Bsearch ( x , A , mid, r ) 2
Image of page 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 understanding why the algorithm is correct.
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

What students are saying

  • Left Quote Icon

    As a current student on this bumpy collegiate pathway, I stumbled upon Course Hero, where I can find study resources for nearly all my courses, get online help from tutors 24/7, and even share my old projects, papers, and lecture notes with other students.

    Student Picture

    Kiran Temple University Fox School of Business ‘17, Course Hero Intern

  • Left Quote Icon

    I cannot even describe how much Course Hero helped me this summer. It’s truly become something I can always rely on and help me. In the end, I was not only able to survive summer classes, but I was able to thrive thanks to Course Hero.

    Student Picture

    Dana University of Pennsylvania ‘17, Course Hero Intern

  • Left Quote Icon

    The ability to access any university’s resources through Course Hero proved invaluable in my case. I was behind on Tulane coursework and actually used UCLA’s materials to help me move forward and get everything together on time.

    Student Picture

    Jill Tulane University ‘16, Course Hero Intern