---
title: "判断给定的一个数字x是否在指定的一个有序的数字序列中存在[递归方式]"
author: "lxwt909"
date: "2016-12-12T15:20:50Z"
tags: ["Java"]
categories: ["编程语言"]
slug: "x"
draft: false
lastmod: "2016-12-12T15:20:50Z"
id: 2344412
url: "https://iamyida.iteye.com/blog/2344412"
---

```
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);
    }
}
```