Java BinarySearch

markdown #說明 二元搜尋法,是將資料分成兩半,由中間開始搜尋,並且比較大小,太小往大的那邊搜尋、太大往小的那邊搜尋。 #操作流程 ##Code ``` import java.io.*; class Searcher{ int [] data; int item; int search(int[] data,int item) { this.data=data; this.item=item; return BSearch(0,data.length-1); //test } int BSearch(int low ,int high){ if (low> high) { return -1; } int middle=(low + high)/2 ; if (item ==data[middle]) { return middle; } else if (item>data[middle]) { return BSearch(middle+1,high); } else { return BSearch(low,middle-1); } } } public class BSearch { public static void main(String[] argv)throws IOException { Searcher a= new Searcher(); System.out.print("please input what you want to find\n->"); BufferedReader br =new BufferedReader(new InputStreamReader(System.in)); int target =java.lang.Integer.parseInt(br.readLine()); int i =a.search(new int []{3,5,7,8,10,34,56},target); if (i==-1) { System.out.println("Didn't find it"+target); } else { System.out.println("in the "+ i +" location find target "+ target ); } } } ``` ##Demo
- Code

留言