1.4.10
Posted w-j-c
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了1.4.10相关的知识,希望对你有一定的参考价值。
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的主要内容,如果未能解决你的问题,请参考以下文章