Search method to search while narrowing the range in half

Search speed is fast

Data needs to be sorted in advance

`BinarySerch.java`

```
class BinarySerch{
public static void main(String[] args){
//Sorted array to search
int a[] = {1,3,6,8,10};
//Value to search
int serchValue = 3;
//The sequence number of the found data The initial value is an error value (-1）
int find = -1;
//Leftmost and rightmost numbers to search
int left = 0;
int right = a.length-1;
//Repeat when there is data on the left and right edges to check
while(left <= right){
//Specify the position to check the number in the middle of the left and right
int middle = (int)((left + right)/2);
//Compare the value of the position to look for with the position to look for
if(a[middle] == serchValue){
//If they are the same, save the number and end the iteration
find = middle;
break;
}else if (a[middle] < serchValue){
//If it is smaller than the value you are looking for, move the left edge
left = middle + 1;
}else {
//If it is larger than the value you are looking for, move the right edge
right = middle - 1;
}
}
//Display search results
System.out.println("search results:" + find);
}
}
```

Reference book [Enjoyable learning algorithm and programming pictorial book](https://www.amazon.co.jp/%E6%A5%BD%E3%81%97%E3%81%8F%E5%AD%A6%E3%81] % B6-% E3% 82% A2% E3% 83% AB% E3% 82% B4% E3% 83% AA% E3% 82% BA% E3% 83% A0% E3% 81% A8% E3% 83% 97% E3% 83% AD% E3% 82% B0% E3% 83% A9% E3% 83% 9F% E3% 83% B3% E3% 82% B0% E3% 81% AE% E5% 9B% B3% E9% 91% 91-% E6% A3% AE-% E5% B7% A7% E5% B0% 9A-ebook / dp / B01N56TW48)

Recommended Posts