Java 實現折半查找

 1 package search;
 2 import java.util.*;
 3 /*折半查找要求線性表是有序的,假設遞增
 4  * 基本思路:R[low...high]是當前的查找區間,首先肯定中間位置mid=(low+high)/2,將待查關鍵字k與R[mid]比較,
 5  * 若相等查找成功,若R[mid]>k,則新的查找區間爲R[low...mid-1],若R[mid]<k,則新的查找區間爲R[mid+1...high],
 6  * 相同的方式處理新的區間,直到區間的長度小於1,查找結束*/
 7 public class zhebansearch {
 8 
 9     public static void main(String[] args){
10         Scanner cin = new Scanner(System.in);
11         String[] str=new String[2];
12         for(int i=0;i<2;i++){
13             str[i] = cin.nextLine();
14         }        
15         String[] st = str[0].split(" ");
16         int[] c = new int[st.length];
17         for(int i=0;i<c.length;i++){
18             c[i]=Integer.parseInt(st[i]);
19         }
20         int key = Integer.parseInt(str[1]);
21         int result = search(c,key);
22         System.out.print(result+1);//找到返回相應索引值(從1開始),沒找到返回1
23     }
24     public static int search(int[] R,int k){
25         int length = R.length;
26         int mid,low=0,high=length;
27         while(low<=high){
28             mid = (low+high)/2;
29             if(R[mid]==k){
30                 return mid;
31             }else if(R[mid]>k){
32                 high=mid-1;
33             }else{
34                 low=mid+1;
35             }
36         }
37         return -1;
38     }
39 }

 

控制檯輸入:第一個行輸入要查找的序列,第二行輸入要查找的關鍵字。例如:1 12 33 35 45 6733結果爲:3
相關文章
相關標籤/搜索