Binary search (Java)

Keywords: Java

Binary search

Binary search

A set of ordered numbers. Find the position of one of the numbers (value). Store the data according to the array (int[] a). The index of the array refers to the number to be searched. Use three variables to store the index of the first position (start), the last position (end) and the middle position (MID). For each search, the array value represented by the mid index is used to compare with the value to be searched. If the value at the mid index (a[mid]) is greater than the value to be searched, the search range is placed in the first half of the search (that is, the index at the last position is moved to the previous position of the middle index [end = mid-1]). If the value at the middle index (a[mid]) is greater than the value to be searched If the array of indexes (a[mid]) is smaller than the value to be searched), then the search range will be placed in the second half of the search (that is, the index of the first position will be moved to the next position of the middle index [start = mid+1]).

 

 1 package cn.sxt.oo;
 2 
 3 import java.util.Arrays;
 4 import java.util.Scanner;
 5 
 6 /**
 7  * Test binary search
 8  * @author Trista
 9  *
10  */
11 public class BinarySearch1 {
12     public static void main(String[] agrs) {
13         int[] a = {12,45,98,76,56,4,5,7,1,0,13,99,66};
14         Scanner sc = new Scanner(System.in);
15         System.out.println("Enter the number you want to find:");
16         int value = sc.nextInt();
17         Arrays.sort(a);
18         load(value,a);
19         
20         
21     }
22 
23     public static void load(int value,int[] b) {
24         int begin = 0;
25         int last = b.length-1;
26         boolean flag = true;    
27        while(last>=begin) {
28             int mid = (begin+last)/2;
29                 if(value==b[mid]) {
30                     flag = false;
31                     System.out.println("From small to large, the value in the value is the first"+(mid+1)+"position");
32                 }
33                 if(value>b[mid]) {
34                     begin = mid+1;
35                 }else {
36                     last =mid-1;
37                 }
38             }
39        if(flag) {
40            System.out.println("The value does not exist");
41        } 
42     }
43 }

Posted by Matt Kindig on Sun, 08 Dec 2019 11:02:03 -0800