1.概念
給定數組,必須有自然順序,從中取某個元素的索引,與中間的數字進行比較
2.代碼實現:
package com.itcast.Text03;
public class Text02 {
public static void main(String[] args) {
int[] arr = {10,20,30,40,50,60,70,88,90};
int key = 88;
int binary = binary(arr, key);
System.out.println(binary);
}
public static int binary(int[] arr, int key) {
int left = 0;
int right = arr.length - 1;
while (left < right) {
int middle = (left + right) / 2;
if (arr[middle] > key) {
right = middle - 1;
} else if (arr[middle] < key) {
left = middle + 1;
} else {
return middle;
}
}
return -1;
}
}