[JAVA] BinarySearchNoRecursion - 二分搜尋

非遞迴式二分搜尋

package utitled;

public class BinarySearchNoRecursion {

    public static void main(String[] args) {
        int[] arr = {1,3,7,8,13,67,100};
        int i = binarySearch(arr, 7);
        System.out.println("i = " + i);

    }

    /**
     * 二分搜尋(非遞歸)
     * @param arr 待搜尋陣列(升序)
     * @param target 目標值
     * @return 目標值索引
     */
    private static int binarySearch(int[] arr, int target) {
        int left = 0;
        int right = arr.length - 1;

        while (left <= right) {
            int mid = (left + right) / 2;
            if (target == arr[mid]) {
                return mid;
            } else if (target < arr[mid]) {
                // 向左查找
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }
        return -1;
    }
}

如有敘述錯誤,還請不吝嗇留言指教,thanks!