码迷,mamicode.com
首页 > 其他好文 > 详细

1.4.10

时间:2018-06-03 14:31:23      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:lse   oid   span   std   return   str   sea   style   modify   

question:

Modify binary search so that it always returns the element with the smallest index that mathes the search element (and still guarantees logarithmic running time).

answer:

//注意二分查找一定要是有序数组!!!(我搞忘记了,然后怎么都查不出错QAQ)

import edu.princeton.cs.algs4.*;

public class BinarySearch
{
    public static int Rank(int key, int[]a, int lo, int hi)
    {
        if(lo > hi)
            return -1;
        int mid = lo + (hi - lo)/2;
        if(a[mid] == key) 
        {
            int min = Rank(key, a, lo, mid-1);
            if(min != -1)
                return min;
            return mid;
        }
        else if(a[mid] > key)
            return Rank(key, a, lo, mid-1);
        else
            return Rank(key, a, mid+1, hi);
    }

    
    public static void main(String[] args)
    {
        int a[] = {0,0,1,1,2,4,5,5,6,8,9,10};//二分查找必须是有序数组!!!
        int key = 1;
        int ans = Rank(key,a,0,a.length-1);
        StdOut.println(ans);
    }
}

 

1.4.10

标签:lse   oid   span   std   return   str   sea   style   modify   

原文地址:https://www.cnblogs.com/w-j-c/p/9128715.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!