判断给定的一个数字x是否在指定的一个有序的数字序列中存在[二分查找方式]

package tree.binarytree;

/**
 * Created by Lanxiaowei
 * Craated on 2016/12/12 13:51
 * 判断给定的一个数字x是否在指定的一个有序的数字序列中存在
 * 采用二分查找方式实现
 */
public class Test4 {

    public static void main(String[] args) {
        int x = 16;
        int[] array = {1,2,3,4,5,6,7,8,9,10};
        boolean exists = search(x,array);
        System.out.println(exists);
    }

    public static boolean search(int x,int[] array) {
        if(null == array || array.length == 0) {
            return false;
        }
        int from = 0, to = array.length - 1;
        if(from > to) {
            return false;
        }
        int mid = 0;
        while (from <= to) {
            mid = (from + to) / 2;
            if(array[mid] == x) {
                return true;
            }
            //如果array[mid] > x,则表明x在中间值的左边,
            if(array[mid] > x) {
                to = mid - 1;
            } else {
                from = mid + 1;
            }
        }
        return false;
    }
}

猜你喜欢

转载自iamyida.iteye.com/blog/2344415
今日推荐