Created
December 11, 2012 02:56
-
-
Save richzw/4255542 to your computer and use it in GitHub Desktop.
Find the number from descending order array with left rotate N element
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
5 /** | |
6 * @func: the binary search fur descending order array. | |
7 */ | |
8 int binary_search(int arr[], int left, int right, int val){ | |
9 int ret = -1; | |
10 if (NULL == arr || left >= right) | |
11 return ret; | |
12 | |
13 while(left <= right){ | |
14 int middle = (left & right) + ((left ^ right) >> 1); | |
15 if (val == arr[middle]){ | |
16 ret = middle; | |
17 break; | |
18 }else if (arr[middle] > val){ | |
19 left = middle + 1; | |
20 }else { | |
21 right = middle - 1; | |
22 } | |
23 } | |
24 return ret; | |
25 } | |
26 | |
27 /** | |
28 * @func: find the number from descending order array with left rotate N element. | |
29 * @param {int} val, the number should be found | |
30 * @param {array} arr, the array with different numbers and which the number should be found. | |
31 * @param {int} left, the left boundary of the array. | |
32 * @param {int} right, the right boundary of the array. | |
33 * @return {int}, the index of number in this array. | |
34 * -1 indicates this number cannot be found in the array. | |
35 */ | |
36 int find_from_orderarray(int val, int arr[], int left, int right){ | |
37 int ret = -1; | |
38 if (NULL == arr || left >= right) | |
39 return ret; | |
40 | |
41 int middle = (left & right) + ((left ^ right) >> 1); | |
42 if (val == arr[middle]){ | |
43 return middle; | |
44 } | |
45 if (val == arr[left]){ | |
46 return left; | |
47 } | |
48 if (val == arr[right]){ | |
49 return right; | |
50 } | |
51 | |
52 if (arr[left] > arr[middle]){ | |
53 if( val > arr[middle] && val < arr[left]){ | |
54 // It is descending order array from left to middle, find val by binary search. | |
55 ret = binary_search(arr, left, middle, val); | |
56 } else { | |
57 // Just like another same array from middle to right. | |
58 ret = find_from_orderarray(val, arr, middle, right); | |
59 } | |
60 }else { | |
61 if ( val < arr[middle] && val > arr[right]){ | |
62 ret = binary_search(arr, middle, right, val); | |
63 } else { | |
64 ret = find_from_orderarray(val, arr, left, middle); | |
65 } | |
66 } | |
67 return ret; | |
68 } | |
69 | |
70 int main(){ | |
71 int array[] = {4, 3, 2, 1, 10, 9, 8, 7, 6, 5}; | |
72 cout << "the 2 are in the " << find_from_orderarray(2, array, 0, sizeof(array)/sizeof(array[0]) - 1) << endl; | |
73 return 0; | |
74 } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment