二分查找(非递归)

/**
* 二分查找
*
* @param arr 数组需要升序排列
* @return 数组下标
*/
private static int binarySearch(int[] arr, int target) {
int left = 0;
int right = arr.length - 1;

    while (left <= right) {
        int mid = left + (right - left) / 2;
        if (arr[mid] == target) {
            return mid;
        }
        if (target < arr[mid]) {
            right = mid - 1;
        } else if (target > arr[mid]) {
            left = mid + 1;
        }
    }
    return -1;
}
posted @ 2022-04-24 21:39  CoderCatIce  阅读(16)  评论(0编辑  收藏  举报