`
lxwt909
  • 浏览: 566830 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

判断给定的一个数字x是否在指定的一个有序的数字序列中存在[递归方式]

阅读更多
package tree.binarytree;

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

    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,0,array.length - 1,array);
        System.out.println(exists);
    }

    public static boolean search(int x,int from, int to,int[] array) {
        if(null == array || array.length == 0) {
            return false;
        }
        if(from > to) {
            return false;
        }
        int mid = (from + to) / 2;
        //如果刚好中间那个元素就是数字x
        if(array[mid] == x) {
            return true;
        }
        if(array[mid] > x) {
            return search(x,from,mid - 1,array);
        }
        return search(x,mid + 1,to,array);
    }
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics