What do you know about binary search?

Source: Internet
Author: User

Copyright. For more information, see the source. Thank you!
Http://blog.csdn.net/walkinginthewind/article/details/8937978

Binary Search, one of the most basic algorithms, is also the focus of the interview, because the basic algorithms best reflect whether a person's foundation is solid. This article provides a summary of the problem related to binary search.

Question list:

1. Given an ordered (non-descending) array A, evaluate any I so that a [I] is equal to the target. If it does not exist,-1 is returned.
2. Given an ordered (non-descending) array A, which can contain duplicate elements, the minimum I is obtained so that a [I] is equal to the target. If it does not exist,-1 is returned.
3. Given an ordered (non-descending) array A, which can contain duplicate elements, the maximum I is obtained so that a [I] is equal to the target. If it does not exist,-1 is returned.
4. Given an ordered (non-descending) array A, which can contain duplicate elements, the maximum I is obtained so that a [I] is smaller than target. If no such element exists,-1 is returned.
5. Given an ordered (non-descending) array A, which can contain duplicate elements, the minimum I is obtained so that a [I] is greater than the target. If no such element exists,-1 is returned.
6. Given an ordered (non-descending) array a, it can contain repeated elements and calculate the number of times the target appears in the array.
7. Given an ordered (non-descending) array A, if the target appears in the array, the return position. If it does not exist, the return position should be inserted.
8. Given an ordered (non-descending) array a, it can contain duplicate elements and locate the element with the smallest absolute value.
9. given an ordered (non-descending) array A and an ordered (non-descending) array B, it can contain repeated elements and obtain the K (k> = 0) in the result of merging the two arrays) number.
10. an ordered (ascending) array with no repeated elements. After a position is rotated, locate the position of the target in the changed array. If no position exists,-1 is returned.
11. An ordered (ascending) array with no repeated elements. After a certain position is rotated, locate the minimum value.
12. An ordered (ascending) array with no repeated elements. After a certain position is rotated, find the small element K (k> 0 ).

1. Given an ordered (non-descending) array A, evaluate any I so that a [I] is equal to the target. If it does not exist,-1 is returned.
This is the most primitive binary search question. It uses the ordered attribute of the array to split the semi-query, so that the search time complexity is O (logn ). See Implementation Code and comments.

Int search (int A [], int N, int target) {int low = 0, high = n-1; while (low <= high) {// note: if you use (low + high)/2 to find the intermediate position, it is easy to overflow int mid = low + (high-low)> 1); if (a [Mid] = target) return mid; else if (a [Mid] <target) Low = Mid + 1; else // A [Mid]> targethigh = mid-1;} return-1 ;}

2. Given an ordered (non-descending) array A, which can contain duplicate elements, the minimum I is obtained so that a [I] is equal to the target. If it does not exist,-1 is returned.
This is the first time that target appears in the array. Here, someone may want to directly use the original binary search. If no binary search exists,-1 is returned. If yes, locate the leftmost position that is equal to the target value range in sequence, in the worst case, the complexity is O (n), and it does not take full advantage of binary search. For details about the solution here, refer to the implementation code and comments.

Int searchfirstpos (int A [], int N, int target) {int low = 0, high = n-1; while (low 

3. Given an ordered (non-descending) array A, which can contain duplicate elements, the maximum I is obtained so that a [I] is equal to the target. If it does not exist,-1 is returned.

This is the final position of the target in the array. This is basically the same as the previous question, but you should pay attention to it. For more information, see implementation code and comments.

Int searchlastpos (int A [], int N, int target) {int low = 0, high = n-1; while (low 

4. Given an ordered (non-descending) array A, which can contain duplicate elements, the maximum I is obtained so that a [I] is smaller than target. If no such element exists,-1 is returned.

That is, to find the location of the largest element smaller than the target. See Implementation Code and comments.

Int searchlastposlessthan (int A [], int N, int target) {int low = 0, high = n-1; while (low 

5. Given an ordered (non-descending) array A, which can contain duplicate elements, the minimum I is obtained so that a [I] is greater than the target. If it does not exist,-1 is returned.
That is, to find the position of the smallest element greater than the target. See Implementation Code and comments.

Int searchfirstposgreaterthan (int A [], int N, int target) {int low = 0, high = n-1; while (low 

6. Given an ordered (non-descending) array a, it can contain repeated elements and calculate the number of times the target appears in the array.

Find the first and last appearance positions. Since the previous implementation has been completed, I will not explain it here. See Implementation Code and comments

Int count (int A [], int N, int target) {int firstpos = searchfirstpos (A, N, target); // If (firstpos =-1) return 0; int lastpos = searchlastpos (A, N, target); // return lastpos-firstpos + 1; // number of occurrences}

This topic description can be changed to evaluate the index range of the target value in the array.

7. Given an ordered (non-descending) array A, if the target appears in the array, return the position. If it does not exist, return the position where it should be inserted.

For example, [1, 3, 5, 6], 5 → 2
[1, 3, 5, 6], 2 → 1
[1, 3, 5, 6], 7 → 4
[1, 3, 5, 6], 0 → 0

Int searchinsert (int A [], int N, int target) {// if it is larger than the maximum value, the insert position is NIF (A [n-1] <target) return N; int low = 0, high = n-1; while (low 

8. Given an ordered (non-descending) array a, it can contain duplicate elements and locate the element with the smallest absolute value.

Find the first position greater than or equal to 0, and then compare it with the absolute value of the previous element, return the position of the element with a smaller absolute value. See Implementation Code and comments

Int searchminabs (int A [], int N) {int low = 0, high = n-1; while (low 

9. given an ordered (non-descending) array A and an ordered (non-descending) array B, it can contain repeated elements and obtain the K (k> = 0) in the result of merging the two arrays) number.

There are two arrays in this question, which are ordered. In any case, we should first consider whether binary search is feasible. If sequential search is used, the minimum time complexity is O (k), which is similar to the merge process in Merge Sorting. The time complexity of binary search is O (logm + logn ). For the specific implementation process of binary search, see implementation code and annotations.

Int findkthin2sortedarrays (int A [], int M, int B [], int N, int K) {If (M <= 0) // array A has no elements, directly find the K element in B. Return B [k]; If (n <= 0) // array B has no elements, directly find the K element return a [k]; int I = (S-1)> 1; // The intermediate position of array a Int J = (n-1)> 1; // The intermediate position of array B if (a [I] <= B [J]) // The intermediate element of array a is smaller than or equal to the intermediate element of array B {/* set X to the number of elements in array A and array B smaller than B [J, then I + 1 + J + 1 is less than or equal to X, because there may be elements less than or equal to B [J] in a [I + 1] to M-1; if K is smaller than I + 1 + J + 1, the K element to be searched must be smaller than or equal to B [J], because X is greater than or equal to I + 1 + J + 1; since the k-th element is less than or equal to B [J ], A [0] ~ A [M-1] and B [0] ~ Find the K element in B [J] and call it recursively. */If (k <I + 1 + J + 1) {If (j> 0) return findkthin2sortedarrays (a, m, B, J + 1, k ); else // J = 0 special processing to prevent endless loops {If (k = 0) return min (A [0], B [0]); if (k = m) return max (A [M-1], B [0]); return a [k] <B [0]? A [k]: max (A [k-1], B [0]);} /* If y is set to array A and array B, it is smaller than the number of elements equal to a [I], then I + 1 + J + 1 is greater than or equal to Y; if K is greater than or equal to I + 1 + J + 1, find that the K element must be greater than a [I], because I + 1 + J + 1 is greater than or equal to Y; since the k-th element is greater than a [I], you only need to A [M-1] and B [0] ~ Find the k-i-1 element in B [n-1] and call it recursively. */Elsereturn findkthin2sortedarrays (a + I + 1, m-i-1, B, n, k-i-1);} // If the intermediate element of array A is greater than the intermediate element of array B, then switch array A and B and call elsereturn findkthin2sortedarrays (B, n, a, m, k) again );}

10. An ordered (ascending) array with no repeated elements. After a position is rotated, locate the position of the target in the changed array. If the position does not exist, return-1.

For example0
1 2 4 5 6 7
May become4
5 6 7 0 1 2

First, we will compare whether the intermediate element is the target value, if it is the return position. If not, we should try to reduce the number of search zones by half. As rotation changes exist, we need to make more judgments. We know that there is only one rotation change, so there must be an ordered sub-array on both sides of the intermediate element, so we can determine whether the target is in this ordered sub-array, to search for this sub-array or another sub-array. For more information, see implementation code and comments.

Int searchinrotatedarray (int A [], int N, int target) {int low = 0, high = n-1; while (low <= high) {int mid = low + (high-low)> 1); if (a [Mid] = target) return mid; if (A [Mid]> = A [low]) {// low ~ Mid is the ascending if (target> = A [low] & target <A [Mid]) High = mid-1; elselow = Mid + 1 ;} else {// mid ~ High is the ascending if (target> A [Mid] & target <= A [High]) Low = Mid + 1; elsehigh = mid-1 ;}} return-1 ;}

If such an array contains repeated elements, can we still use binary? The answer is no. See several examples.

[1, 2, 2, 2], [2, 1, 2, 2], [2, 2, 1, 2, 2], [2, 2, 2, 1, 2], [2, 2, 2, 2, 1], all of which come from a change when the first array is rotated, we cannot determine whether element 1 exists by means of binary.

11. An ordered (ascending) array with no repeated elements. After a certain position is rotated, locate the minimum value.

If the middle element is smaller than the left end element, the minimum value is within the left half interval (including the middle element). If the middle element is greater than the right end element, the minimum value is within the right half interval (including the middle element ). See Implementation Code and comments.

Int searchmininrotatedarray (int A [], int N) {If (n = 1) return 0; int low = 0, high = n-1; while (low 

12. An ordered (ascending) array with no repeated elements. After a certain position is rotated, find the position of the small element K (k> 0 ).
We can use the answer to the previous question to find the location of the minimum value, and then we can find the K-small element. See Implementation Code and comments

int searchKthInRotatedArray(int A[], int n, int k) {int posMin = searchMinInRotatedArray(A, n);return (posMin+k-1)%n;}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.