Two-point search
The binary lookup algorithm is a search algorithm that finds a particular element in an ordered array. The search process starts at the middle element of the array, and if the intermediate element is exactly the element to be found, the searching process ends, and if a particular element is greater than or less than the middle element, it is found in the half of the array greater than or less than the middle element, and is compared with the beginning of the intermediate element. If an array of steps is empty, the representation cannot be found. Each comparison of this search algorithm reduces the search scope by half. Binary search reduces the search area by half, with a time complexity of 0 (LOGN).
The advantage of binary search is that the number of comparisons is small, the searching speed is fast, the average performance is good, the disadvantage is that the unknown Origin table is ordered and the insertion and deletion is difficult. Therefore, binary search is a method to find the optimal solution of the problem by shrinking the possible range of solution , and it is suitable for an ordered list which is frequently changed. binary search algorithm requires sequential storage structure must be ordered by the size of the keyword binary search algorithm flowchart
Binary search Flowchart binary search C source code
Recursive version of binary lookup
int binary_search_recursion (const int array[], int low, int higher, int key)
{
int mid = low + (high -low)/2;
if (Low > High)
return-1;
else{
if (array[mid] = = key)
return mid;
else if (Array[mid] > key)
return Binary_search_recursion (array, low, mid-1, key);
else
return binary_search_recursion (array, mid+1, high, key);
}
}
Cyclic version of binary lookup
int binary_search_loop (const int array[], int len, int key)
{int low
= 0;
int high = len-1;
int mid;
while (low <= high) {
mid = (Low+high)/2;
if (array[mid] = = key)
return mid;
else if (Array[mid] > key) high
= Mid-1;
else low
= mid + 1;
}
return-1;
}
Boundary Error
The boundary of binary search algorithm is generally divided into two kinds of situations, one is left closed right open interval, such as [Low,high], one is left closed right closed interval, such as [Low,high]. It is important to note that the initialization conditions outside the loop, and the iterative steps in the loop body, must conform to the consistent interval rules, that is, if the loop body is initialized with the left closed right open interval as the boundary, so should the iteration inside the loop body. Leetcode Instances Search in rotated Sorted Array Requirements
Suppose a sorted array is rotated at some pivot unknown to you beforehand
Suppose there is a well-ordered array, which is rotated at some pivot point beforehand
(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. Analysis
Two-point search, the difficulty lies in the determination of left and right boundary
If A[middle] <= A[first], then the sub-array of the [middle,last-1] interval is an ascending sequence, then it can be queried by the method of binary lookup; otherwise, it will be further divided, knowing that the subarray is an incremented array. The reverse is the same thing.
Since last always points to the next position in the final element of the subarray, it is important to pay special attention to the assignment of the program. C + + code
Class Solution {public
:
int search (int a[], int n, int target) {
int first = 0;
int last = n;
while (first! =)
{
int middle = (first + last)/2;
if (a[middle] = = target)
return middle;
if (A[first] >= A[middle]) {
if (Target > A[middle] && target <= a[last-1]) First
= middle+1;< C12/>else Last
= middle;
}
else
{
if (target < A[middle] && target >= A[first]) Last
= middle;
else First
= middle+1;
}
}
return-1;
}
};
Search in rotated Sorted Array II
Requirements
Follow up for ' Search in rotated Sorted Array ': What if duplicates is allowed?
Write a function to determine if a given the target was in the array.
As a variant of the previous question, this topic allows for the existence of duplicate element analysis
Allow repeating elements, if a[middle]>=a[left] in the previous question, then [Left,middle] is the assumption that the increment sequence cannot be established, such as [1,3,1,1,1].
If A[M]>=A[L] cannot be determined to increment, then split it into two conditions: if A[M]>A[L], then the interval [l,m] must increment if A[M]==A[L] can not be determined, then l++, look down one step. C + + code
Class Solution {public
:
bool Search (int a[], int n, int target) {
int first = 0,last = N;
while (first! = last)
{
int mid = (first+last)/2;
if (a[mid] = = target)
return true;
if (a[mid] = = A[first])
first++;
else if (A[mid] > A[first])
{
if (a[first]<= target && A[mid] > target) Last
= mid;
else First
= mid+1;
}
else
{
if (A[mid] < target && A[last-1] >= target) First
= mid+1;
else last
= mid;
}
}
return false;
}
};
the application of two-point search idea
finding the optimal solution problem
The binary search method is also useful for solving the problem of optimal solution. For example, "to satisfy a certain condition C (x) the smallest X" problem. For any x that satisfies the C (x), if all X ' >=x also satisfies C (X '), the smallest x can be obtained using a binary lookup.
First we initialize the left endpoint of the interval to a value that does not satisfy the C (x), and the right endpoint is initialized to a value that satisfies C (x). Then each time you take the midpoint mid= (LB+UB)/2, determine if C (mid) meets and narrows until (Lb,ub] is small enough. The last UB is the minimum value required.
Similarly, the maximization of the problem can be solved in the same way. assume a solution and determine whether it is feasible
There are n ropes, they are li respectively in length. If you cut a rope with the same length of k from them, the K-string will be the longest of each piece. The answer is reserved to 2 digits after the decimal point.
restrictions : 1<= N <= 10000 1<= K <= 10000 1<= Li <= 100000 analysis
The condition is c (x) = a rope with k length x can be obtained
The problem becomes the largest x that satisfies the C (x) condition. When the interval is initialized, the Nether is lb=0 and the upper bound is ub=inf.
Transformation:
Because the length of the Li rope can be cut out of the floor (li/x) segment length x rope, so
C (x) = (the sum of Floor (li/x) is greater than or equal to K) code instance
#include <iostream>
#include <math.h>
using namespace std;
#define MAX_N
int N = 4;
int K = ten;
Double L[max_n] = {8.02,7.43,4.57,5.39};
BOOL C (double x)
{
int num = 0;
for (int i=0;i<n;i++)
{
num + = (int) (l[i]/x);
}
return num >= K;
}
void Solve ()
{
double lb = 0;
Double UB = +;
for (int i=0;i<100;i++)
{
double mid = (Lb+ub)/2;
if (C (mid)) lb = mid;
else UB = mid;
}
cout << Floor (ub*100)/100<<endl;
}
int main () {
solve ();
return 0;
}
end-of-point determination of binary search
In the problem of outputting decimals, the allowable error range is generally established or the number of digits following the decimal point in the output. It is necessary to set reasonable end conditions to meet the requirements of precision.
In the above procedure, we set the number of cycles as the termination condition. 1 cycles can be reduced by half of the interval range, 100 cycles can reach 10-30 power of the accuracy range, basically no problem. Maximize Average
The weight and value of n items are WI and VI respectively. The value of the unit weight is maximized by selecting K items from it.
Restrictions: 1<= k <= n <= 10^4 1<= wi,vi <= 10^6 Analysis
Maximizing the average code instance
Input
int n,k;
int w[max_n],v[max_n];
Double y[max_n];//v-x * W
bool C (double x)
{for
(int i=0;i<n;i++) {
y[i] = v[i]-x*w[i];
}
Sort (y,y+n);
Compute the sum of top-k number (array y)
double sum = 0;
for (int i=0;i<k;i++) {
sum+=y[n-i-1];
}
return sum >= 0;
}
void Solve ()
{
double lb=0,ub=inf;
for (int i=0;i<100;i++) {
double mid = (Lb+ub)/2;
if (C (mid))
lb = mid;
else
UB = mid;
}
printf ("%.2f\n", UB);
}