Java Binary Search

import java.util.Arrays;



publicclass BinarySearch {



// precondition: array a[] is sorted

publicstaticintrank(int key,int[] a){

int lo =0;

int hi = a.length -1;

while(lo <= hi){

// Key is in a[lo..hi] or not present.

int mid = lo +(hi - lo)/2;

if(key < a[mid]) hi = mid -1;

elseif(key > a[mid]) lo = mid +1;

elsereturn mid;

}

return-1;

}



publicstaticvoidmain(String[] args){

int[] whitelist = In.readInts(args[0]);



 Arrays.sort(whitelist);



// read key; print if not in whitelist

while(!StdIn.isEmpty()){

int key = StdIn.readInt();

if(rank(key, whitelist)==-1)

 StdOut.println(key);

}

}

}

你可能感兴趣的:(Binary search)