For a traditional binary lookup, if it can be found, it returns the subscript of target, and if not found, returns 1, exiting the function. The alignment code is simple, as follows:
intBsearch (vec<int> Vec,intStartintEndinttarget) { intFirst = Start,last =End,mid; while(first<=Last ) {Mid= (first + last) >>1; if(Vec[mid] = = target)returnmid; Else if(Vec[mid] < target) First = mid +1; ElseLast = mid-1; } return-1; }
The above code handles general lookups to meet the requirements, but for some special cases there are limitations, such as duplicates, the search fails to be inserted after ....
The following is a description of the 2 class two-point-finding variants: Prerequisites: Find the number of target,vec[0]<=target<=vec[end], if not in the following nature is not established. The start and end parameters of the function are subscript for the array element, for input vector<int> VEC = {1,2,2,4,4,8,10},start = 0,end = 6; If End = 7, no effect on yes_left and No_right , but it has an effect on the following two cases, especially
Enter:vector<int> VEC = {1,2,2,4,4,8,10};
The lookup successfully returns the leftmost value subscript (yes_left), that is, find 4 returns 3, or the lookup fails, returns the subscript (no_right) of the element in the array that is exactly greater than target, that is, find 3 returns 3, and the 2 case codes are as follows:
intBsearch (vector<int> Vec,intStartintEndinttarget) { intMid,left = Start,right =end; while(left<=Right ) {Mid= (left + right) >>1; if(vec[mid]>=target) Right = mid-1; ElseLeft = mid +1; } returnLeft ;}
Or the above input, find the subscript (yes_right) that successfully returns the rightmost value, that is, find 4 returns 4, or the lookup fails, returns the subscript (no_left) of the element that is exactly less than target in the array, that is, find 3 returns 2, the code is as follows
intBsearch (vector<int> Vec,intStartintEndinttarget) { intMid,left = start,right=end; while(left<=Right ) {Mid= (left + right) >>1; if(vec[mid]>target) Right = mid-1; ElseLeft = mid +1; } returnRight ;}
Feel the Bunker!!
Two-point search and its point of placement