import java.util.Arrays; public class 二分查找 { public static void main(String[] args) { int[] arr = {1, 6, 3, 7, 5}; //排序 for (int i = 0; i < arr.length; i++) { for (int j = i; j < arr.length; j++) { int temp; if (arr[i] > arr[j]) { temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } } int i = BinarySearch(arr, 7); System.out.println(Arrays.toString(arr)); System.out.println("查找到的数据下标为:" + i); } /** * @param arr 要查找的数组 * @param data 要查找的数据 * @return 返回下标 */ public static int BinarySearch(int[] arr, int data) { int begin = 0; int end = arr.length - 1; while (begin <= end) { int mid = (begin + end) / 2; if (data < arr[mid]) { end = mid - 1; } else if (data > arr[mid]) { begin = mid + 1; } else {//arr[mid] = data return mid; } }
//没有找到数据就返回-1 return -1; } }