To learn more about the algorithm series, please refer to the article: summary of dead-knock algorithm
binary search is also called binary algorithm, this algorithm as a classical search algorithm is we have to master the algorithm
This algorithm looks for the premise that the data is ordered, we take the array as an example, we use the binary search method to find the time when we should define three fields:
1.left points to the first array of data
2.right points to the last element of the array
3.mid points to the (left+right)/2 position of the element, is their middle position.
When we want to find a data A in an array, there are a few steps:
- First we compare a to mid, if a is equal to mid then we find the data successfully and the program stops.
- If a is smaller than mid 3rd, if a is larger than mid, step 4th
- Since a is less than mid, the number between mid and right is certainly greater than a, so we ignore them and then point right to the previous position in mid. (You may ask why the previous position does not point to mid, because we have determined that mid is not equal to a, then we do not need to compare him.)
- Since a is greater than mid, then the number between mid and left is definitely smaller than a, so we ignore them and then point to the last position of the mid. (Do not understand can refer to 3 OH)
- If left is not more than right then we have not yet found out, proceed to the first step. If left is already greater than right, then it means that we do not find the data we want in this array.
It is suggested that two-point search is not familiar with the students can first on the draft paper, computer or mind define an ordered array of 0-16 followed by the above steps to find the data 5.
Here is the picture I drew, and look at the steps you've drawn or the steps you've imagined.
If you've seen it, then let's get to the code,
public static voidSelectInt[]num,int a) {Intleft=0;Intright=num.length-1; int m= (left+right)/2; while (left<=right) {if (num[m]==a) {System.out.println ( "in" +m+ "location found"); Return } if (num[m]>a) {right=m-1;} else{left=m+1;} m= (left+right)/2;} System.out.println ( "not Found")}
The method above uses a normal loop, and there is a recursive notation for the two points, which is also shared here.
public static voidSelectInt[]num,int A,IntLeftIntright) {Ifleft>right) {System.out.println ( "not Found"); Return } int m= (left+right)/2; if (num[m]==a) {System.out.println ( "in" +m+ "location found"); Return } if (num[m]>a) {right=m-1; Span class= "Hljs-keyword" >select (num, A,left,right);} else{left=m+1; select (num, A,left,right);}}
The binary search method is said to be finished here. Here warmly remind everyone, learning algorithms, we do not have to rigidly adhere to the implementation of the code, it is meaningless. My advice is to understand the steps in depth, and when you understand the steps, the code is as good as you can play.
Two-part search method of dead-knock algorithm