二分查找(非递归)

  1. 循环重置起始于结束小标
public class HalfSerach {

    public static void main(String[] args) {
        int[] array = {
                1, 3, 5, 7, 9, 11, 13, 15, 17, 19
        };
        HalfSerach hs = new HalfSerach();
        hs.halfSerach(array, 5);
    }

    /**
     * 二分查找,非递归
     */
    public void halfSerach(int[] array, int target) {
        int start = 0;
        int end = array.length - 1;
        int mid = -1;
        while (start < end) {
            mid = (start + end) / 2;
            if (array[mid] == target) {
                break;
            } else if (array[mid] > target) {
                end = mid - 1;
            } else {
                start = mid + 1;
            }
        }
        if (start >= end) {
            mid = -1;
        }
        System.out.println(mid);
    }
}

你可能感兴趣的:(二分查找(非递归))