Binary search (Java implementation)

Time:2022-1-3

Are you learning data structure? I didn’t learn C and only knew Java. I said the algorithm was so difficult.

No more nonsense. I share a very simple binary search. To find variables of type T in an ordered array (sorted from small to large), I directly use int. the first element of the array (the element with subscript 0) is not used. The actual search starts from the second element (the element with subscript 1).

The whole code is divided into two parts.

1. Methods

1 /*
 2 * dichotomy finds variable K in an ordered array
 3  */
 4 public class BinarySearch {
 5 
 6     /*
 7 * the return value of the method is the subscript of the element to be found. If there is no element K to be found in the array, it returns - 1
 8      */
 9     int binarySearch(int[] array,int k) {
10         int left,right,mid;
11         final int NotFound=-1;
12         
13         left = 1;  // Initialize left boundary
14         right = array. length-1;  // Initialize right boundary
15         
16         while(left<=right) {
17             mid = (left+right)/2;
18             if(karray[mid]){
21                 left = mid+1;
22             }else {
23                 return mid;
24             }
25         }
26         
27         return NotFound;
28     }
29 }

2. Testing

1 /*
 2 * binary search test class
 3  */
 4 import java.util.*;
 5 public class TestBinarySearch {
 6 
 7     public static void main(String[] args) {
 8         
 9         int[] array = {0,1,6,8,13,24,45,64,76,77,78,90,93};  // Initialize the array. The actual content starts from the second number, that is, the number with subscript 1
10         int index=-1;  // Array index
11         
12         System. out. Print ("please enter the integer you want to find:");
13         Scanner input=new Scanner(System.in);
14         int intentNum=input.nextInt();
15         
16         BinarySearch bs = new BinarySearch();
17         int sub=bs.binarySearch(array,intentNum);
18         
19         if(sub!=-1) {
20             index = sub;
21             System. out. Println (array [index] + "position in the array is" + index);
22         }else {
23             System. out. Println ("the number '+ intentnum +"' was not found.);
24         }
25         
26     }
27 
28 }

The binarysearch () method is the core of the test class.

If this article is useful to you, I hope to praise and support the author. If you have any better views and suggestions, please leave a message in the comment area. Bye, see you next time!