25.03.2013 Views

Cracking the Coding Interview - Fooo

Cracking the Coding Interview - Fooo

Cracking the Coding Interview - Fooo

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Solutions to Chapter 9 | Sorting and Searching<br />

9 3 Given a sorted array of n integers that has been rotated an unknown number of<br />

times, give an O(log n) algorithm that finds an element in <strong>the</strong> array You may assume<br />

that <strong>the</strong> array was originally sorted in increasing order<br />

1 8 1<br />

EXAMPLE:<br />

SOLUTION<br />

Input: find 5 in array (15 16 19 20 25 1 3 4 5 7 10 14)<br />

Output: 8 (<strong>the</strong> index of 5 in <strong>the</strong> array)<br />

We can do this with a modification of binary search<br />

1 public static int search(int a[], int l, int u, int x) {<br />

2 while (l =a [l]) {<br />

10 u = m-1;<br />

11 } else {<br />

12 l = m+1;<br />

13 }<br />

14 }<br />

15 else if (x < a[m]) u = m-1;<br />

16 else if (x

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!