Describe
Suppose a sorted array is rotated on some pivot unknown to you beforehand.
2.1 Array 5
(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
You is given a target value to search. If found in the array is return its index, otherwise return-1.
Assume no duplicate exists in the array.
Binary.h
#include <iostream> #include <assert.h>class solution{public:int search (int a[], int n, int value) {assert (A) ; int start = 0;int end = N-1;while (start<=end) {int mid = (End-start)/2 + start;if (a[mid] = = value) return mid;if (A[start]<=a[mid]) {//ordersif (Value<a[mid]&&value>=a[start]) end = Mid-1;elsestart = mid + 1;} Else{//disorderif (Value>a[mid]&&value<=a[end]) start = mid + 1;else{end = Mid-1;}}} return-1;}};
Binary.cpp
#include "Binary.h" Using namespace std;int main () {int a[9] = { 7, 8, 9, 0, 1, 2, 4, 5, 6 }; Solution s1;cout << s1.search (A, sizeof (a) / sizeof (A[0]), 7) << endl;cout << s1.search (A, sizeof (a) / sizeof (A[0]), 8) << endl;cout << s1.search (A, sizeof (a) / sizeof (A[0]), 9) << endl;cout << s1.search (A, sizeof (a) / sizeof (A[0]), 0) << endl;cout << s1.search (A, sizeof (a) / sizeof (A[0]), 1) << endl;cout << s1.search (A, sizeof (a) / sizeof (A[0]), 2) << endl;cout << s1.search (A, sizeof (a) / sizeof (A[0]), 4) << endl;cout << s1.search (a,&Nbsp;sizeof (a) / sizeof (A[0]), 5) << endl;cout << s1.search (A, sizeof (a) / sizeof (A[0]), 6) << endl;cout << s1.search (A, sizeof (a) / sizeof (A[0]), 3) << endl;system ("pause"); return 0;}
Operation Result:
650) this.width=650; "src=" Http://s2.51cto.com/wyfs02/M02/7F/D3/wKiom1cu1HTAKPfyAAAFoulSndw862.png "title=" 1.PNG " alt= "Wkiom1cu1htakpfyaaafoulsndw862.png"/>
The following is the code for Leetcode_cpp:
650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M01/7F/D1/wKioL1cu1crDLJuZAAC-YJreMmY600.png "title=" 1.PNG " alt= "Wkiol1cu1crdljuzaac-yjremmy600.png"/>
My own program is basically the same as he gave, stating that they still have progress, hehe .... Come on!
< finish >
This article is from the "Zero Egg" blog, please be sure to keep this source http://lingdandan.blog.51cto.com/10697032/1771196
Search in rotated Sorted Array