1. 程式人生 > >1.4.10

1.4.10

binarys The ring lse IT guarantee 註意 IV std

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