27.10.2014 Views

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

<strong>Solutions</strong> to Chapter 9 | Sorting <strong>and</strong> 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 />

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!