package com.example.grokkingalgorithmsdemo.binarysearch;
import lombok.extern.slf4j.Slf4j;
/**
* @Author: Frank
* @Date: 2022-06-04 12:12
*/
@Slf4j
public class BinarySearchJ {
private static Integer binarySearch(int[] list,int item){
int low = 0;
int high = list.length-1;
if (item<list[low] || item>list[high]){
//if smaller than low or bigger than high,
//then meaning not the element in the collection.
log.info("not in this collection,return null");
return null;
}
//當兩個下標還沒有挨在一起或剛剛挨在一起時
while(low<=high){
log.info("start while~~");
//獲取中間數
int mid = (low+high)/2;
//猜測列表中的這個中間數是否是要檢索的數據
int guess = list[mid];
//如果是,直接返回
if(guess==item){
return mid;
}
//如果猜測的數字是大於傳入的要檢索的數字時,
//此時二分查找的策略是,既然中間數不是,那麼就將包括中間數的所有大的數字都排除掉
if(guess>item){
high=mid-1;
}else{
//否則如果猜測的數小於傳入的要檢索的數字時,
//此時二分查找的策略則爲,既然中間數不是,並且真正的數字大於現在猜測的中間數,
//那麼肯定要提高現在的中間數,即將最小部分的數字提升到現中間數+1
low = mid+1;
}
}
return null;
}
/**
* 這些都建立在數據在排好序的情況下,如果不是排好序的情況,需要先進行排序
* 纔可以執行二分查找
* @param args
*/
public static void main(String[] args) {
int[] myList = {1,3,5,7,9};
System.out.println(binarySearch(myList,3)); //1
System.out.println(binarySearch(myList,-1));//null
}
}
在二分查找算法中,有一個奇怪的地方,當給定要查找數字item,不在這個集合中,
也就是肯定大於最大值或小於集合最小值,那麼肯定是不存在這集合中的。
當加入第15行判定之後,當給定數字-1被算法要求查找後(第55行代碼),會進入if smaller than low or bigger than high的判定。
而如果不加入判定,計算是-1也會進入while循環並執行3次。