Java - 陣列二分搜尋

By sunwc 2023-03-19 Practice
public static void main(String[] args) {
    
    // 二分搜尋
    // 前提:所要搜尋的陣列必須有序
    int[] arr = {-98,-34,2,34,54,66,79,105,210,333};
    int target = 34;
    int startInx = 0;
    int endInx = arr.length-1;
    boolean flag = true;
    while (startInx <= endInx) {
        int middleInx = (endInx - startInx) / 2 + startInx;
        
        if (arr[middleInx] == target) {
            System.out.println("target="+ target+"在index="+middleInx+"找到了!");
            flag = false;
            break;
        } else if (arr[middleInx] < target) {
            startInx = middleInx + 1;
        } else if (arr[middleInx] > target) {
            endInx = middleInx - 1;
        }
    }
    
    if (flag) {
        System.out.println("很遺憾沒找到");
    }
        
}
	

輸出結果

target=34在index=3找到了!
  • array中常見的異常(Exception):
    • 陣列索引越界:ArrayIndexOutOfBoundsException