美文网首页
BinarySearch2

BinarySearch2

作者: 賈小強 | 来源:发表于2018-03-28 11:03 被阅读14次

    简书 賈小強
    转载请注明原创出处,谢谢!

    package com.lab1.test3;
    
    public class BinarySearch2 {
        public static void main(String[] args) {
            int[] a = { 1, 2, 3, 4, 5 };
            int key = 3;
            System.out.println(rank(key, a));
        }
    
        private static int rank(int key, int[] a) {
            return rank(key, a, 0, a.length - 1);
        }
    
        private static int rank(int key, int[] a, int lo, int hi) {
            if (lo > hi) {
                return -1;
            }
            int mid = lo + (hi - lo) / 2;
            if (key < a[mid]) {
                return rank(key, a, lo, mid - 1);
            } else if (key > a[mid]) {
                return rank(key, a, mid + 1, hi);
            } else {
                return mid;
            }
        }
    }
    

    输出

    2
    

    Happy learning !!

    相关文章

      网友评论

          本文标题:BinarySearch2

          本文链接:https://www.haomeiwen.com/subject/vjkycftx.html