Cracking The Coding Interview 9.3
2014-04-28 10:45
302 查看
//Given a sorted array of n integers that has been rotated an unknown number of times, give an O(log n) algorithm that finds an element in the array. You may assume that the array was originally sorted in increasing order. // //EXAMPLE: // //Input: find 5 in array (15 16 19 20 25 1 3 4 5 7 10 14) // //Output: 8 (the index of 5 in the array) #include <iostream> using namespace std; //原始二分法 //int search(int *a, int begin, int end,int key) //{ //int mid; //while(begin < end) //{ // mid = (begin + end)/2; // if (a[mid] == key) // { // return mid; // } // if (key < a[mid]) // { // end = mid; // } // else // { // begin = mid; // } //} //if (begin < end) //{ // int mid = (begin + end)/2; // if (a[mid] == key) // { // return mid; // } // if (key < a[mid]) // { // search(a,begin,mid-1,key); // } // else // { // search(a,mid+1,end,key); // } //} //} int searchInRotate(int *a, int begin, int end,int key) { while(begin < end) { int mid = (begin + end)/2; if (a[mid] == key) { return mid; } if (a[mid] >= a[begin]) { if (key < a[mid] && key >= a[begin]) { end = mid-1; } else { begin = mid+1; } } else { if (key > a[mid] && key <a[begin]) { begin = mid + 1; } else { end = mid -1; } } } } int main() { int a[12] = {15,16,19,20,25,1,3,4,5,7,10,14}; //int a[12] = {1,3,4,5,7,10,14,15,16,19,20,25}; //cout<<search(a,0,11,7); cout<<searchInRotate(a,0,11,25); return 0; }
相关文章推荐
- cracking the coding interview No1.1
- Cracking the coding interview--Q1.5
- Cracking The Coding Interview 1.4
- Cracking the coding interview--Q17.3
- Cracking the coding interview--Q19.1
- Cracking The Coding Interview2.4
- cracking the coding interview 中文版
- Cracking the Coding Interview-ch11 | System Design and Memory Limits
- Cracking the coding interview--Q1.8
- Cracking the coding interview--Q3.3
- 【Cracking the coding interview】Q1.8(旋转字符串)
- cracking the coding interview ch1.1
- Cracking the Coding Interview 150题(一)
- cracking the coding interview 中文版
- 《Cracking the Coding Interview》——第8章:面向对象设计——题目7
- 《Cracking the Coding Interview》——第12章:测试——题目6
- Cracking the coding interview--Q20.9
- Cracking the Coding Interview 题目分析笔记—— Array and String
- Cracking the coding interview--Q20.12
- Cracking the coding interview--Q20.13