zoukankan      html  css  js  c++  java
  • 二分查找

    package com.sxc.search;

    import org.junit.Test;

    public class BinarySearch {
    public static int[] array = {1,3,5,7,9,15,13,12,10};//待搜索数组
    public static int search = 9;//待查找数字
    public int getIndex(int begin, int end) {

    int middle = begin + (end - begin)/2;
    if (array[middle] == search){
    return middle;
    }else if (end <= begin){
    return -1;
    }
    else {
    int lertResult = getIndex(begin, middle - 1);
    if (lertResult != -1) {//递归结束条件
    return lertResult;
    } else {
    int rightResult = getIndex(middle + 1, end);//递归实现
    if (rightResult != -1) {
    return rightResult;
    } else {
    return -1;
    }
    }
    }
    }
    @Test
    public void test2(){//测试示例
    BinarySearch m = new BinarySearch();
    int result = m.getIndex(0, array.length-1);
    System.out.println(result);//输出9的下标
    }
    }
  • 相关阅读:
    1022.游船出租
    1021.统计字符
    1020.最小长方形
    1017.还是畅通工程
    1019.简单计算器
    1015.还是A+B
    1014.排名
    1013.开门人和关门人
    1011.最大连续子序列
    1009.二叉搜索树
  • 原文地址:https://www.cnblogs.com/lovenannan/p/9468152.html
Copyright © 2011-2022 走看看