1 package aaa; 2 3 import java.util.Arrays; 4 5 //二分法练习 6 public class Demo { 7 public static void main(String[] args) { 8 // 声明数组 9 int arr[] = { 10, 22, 55, 48, 99, 65, 43 }; 10 // 数组排序 11 Arrays.sort(arr); 12 // 遍历数组 13 for (int i : arr) { 14 System.out.print(i + ","); 15 } 16 //调用方法 17 System.out.println(); 18 System.out.println("指定数字的下标为"+BinarySearch(arr, 22)); 19 } 20 21 //二分的方法 22 public static int BinarySearch(int arr[], int value) { 23 //最大索引下标 24 int max=arr.length-1; 25 //起始索引 26 int min=0; 27 //等分 28 int mid = 0; 29 //第几次二分 30 int n = 0; 31 //循环进行二分法 32 while (min<=max) { 33 n++; 34 mid=(min+max)/2; 35 System.out.println("第"+n+"次等分"+mid); 36 if (arr[mid]==value) { 37 return mid; 38 }else if (arr[mid]>value) { 39 max=mid-1; 40 }else { 41 min=mid+1; 42 } 43 } 44 return -1; 45 } 46 }
![](https://img2020.cnblogs.com/blog/2312973/202104/2312973-20210408210224820-1537907449.png)