好好學習,天天向下
注意:當數據量大、數據爲有序排列、數據不重複時方可使用此法
理解:將一個數組拆分爲兩份,比較查找的數據與數組中間值(數組正中間的一個元素,可能不是正中間)大小關係,如果中間值小於想要查找的數據,那就去數值大的那一份裏面對比,否則就去小的那一份裏面對比
import java.io.Serializable;
import java.util.Arrays;
public class start {
public static void main(String[] args) {
int[] arrayList = {0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
System.out.println(dichotomy(90, arrayList));
}
public static Serializable dichotomy(int key, int[] list) {
int start = 0;
int end = list.length - 1;
while (start <= end) {
int middle = (start + end) / 2;
if (key < list[middle]) {
end = middle - 1;
} else if (key > list[middle]) {
start = middle + 1;
} else {
return middle;
}
}
return "-1";
}
}
總結:雖然沒有排序的數組可以排了序再去查找,那它此時返回的索引是排了序之後的下標,那又該如何是好