Source title: "Design and Analysis of Computer Algorithms", Wang Xiaodong
Set a [0: n-1] is an array row have good sequence, rewrite the binary search algorithm, such that when x is not in the array, return the position of the largest element of x is less than i and greater than a minimum J x element of the position. When searching for an element in an array, i and j the same, both the position x in the array.
Input formats:
Enter two lines:
The first row is n and the value of x; the second line is a non-descending sequence of n different integers, separated by spaces between each integer.
Output formats:
Subscript j is less than the minimum x maximum output element and the maximum index i is greater than the smallest element of x. When searching for an element in an array, i and j same. Tip: If x is less than the full value, the output: -1 0 if x is greater than all the values, the output: the value of n-1, n
Sample input:
Here we are given a set of inputs. E.g:
6 5
2 4 6 8 10 12
Sample output:
Given here corresponding output. E.g:
1 2
——————————————————————————————————分割线——————————————————————————————————————————————
思路:对于能够找到的元素,只需要把这个下标再输出一遍即可。
对于找不到的元素,我们从优化过的二分搜索算法着手。众所周知,二分搜索算法的左指针和右指针会渐渐靠近,如果要输出这个数离得最近的两个下标,不妨分析left和right的接近情况。【这里我用的是left>right的递归条件,这样子做除了简化代码,还有特殊用处】
Each recursive parentheses around the value passed to the parameter of left right.
Get 0: (0,3) -> (0,0) -> (0, -1)
Looking 4: (2,3) -> (3,3) -> (3,2)
Find 6: (2,3) -> (3,3) -> (4,3)
[Remember: mid = (l + r) / 2 will be rounded, mid +1 or -1 every time]
It can be found as long as the left and right front return to reverse the order of two values of -1, the result is the correct output. Here I choose to save the global variable.
Then judgment is not the main function which returns -1, to select a different output.
Time complexity: O (logn) [binary search, not to be construed] space complexity O (n)
Harvest: probably know the idea but can not be untied topic, simulation run inside the brain when you see, might have a windfall.
Finally, attach the code
1 #include<iostream> 2 using namespace std; 3 int leftnum=0; 4 int rightnum=0; 5 int binarysearch(int num[],int left,int right,int chazhao) 6 { 7 //findnum++; 8 int mid; 9 if(left>right) 10 { 11 //cout<<"zhaobudao"; 12 leftnum = left; 13 rightnum = right; 14 return -1; 15 } 16 else 17 { 18 mid=(left+right)/2; 19 if(num[mid]==chazhao) 20 { 21 return mid; 22 } 23 else if(num[mid]!=chazhao) 24 { 25 if(chazhao>num[mid]) 26 { 27 return binarysearch(num,mid+1,right,chazhao); 28 } 29 else return binarysearch(num,left,mid-1,chazhao); 30 } 31 } 32 } 33 34 35 int main() 36 { 37 int num[1000]; 38 int i,chazhao,n; 39 cin>>n; 40 cin>>chazhao; 41 for(i=0;i<n;i++) 42 { 43 cin>>num[i]; 44 } 45 46 int date = binarysearch(num,0,n-1,chazhao); 47 48 if(date == -1){ 49 cout<<rightnum<<" "<<leftnum; 50 51 } 52 else 53 { 54 cout<<date<<" "<<date; 55 } 56 57 }