java實現順序,二分,分塊查詢
阿新 • • 發佈:2018-12-01
二分查詢表一定要有序
下面是具體實現程式碼
import java.util.*; public class search { //順序查詢 public static int seqsearch(int[]a,int keytype){ if(a.length>0){ for(int i=0;i<a.length;i++){ if(a[i]==keytype) //若查詢成功,則返回元素下標i return i; } } return -1; //若查詢不成功,返回-1; } //二分查詢,查詢表必須有序 public static int binarysearch(int[]a,int keytype){ if(a.length>0){ int low=0,high=a.length-1; //查詢範圍的上界和下界 while(low<=high){ int mid=(low+high)/2; //中間位置,當前比較的資料元素位置 if(a[mid]==keytype) //若查詢成功,返回元素下標mid return mid; else if(a[mid]<keytype) //中間元素比給定值小 low=mid+1; //查詢範圍縮小到後半段 else //中間元素比給定值大 high=mid-1; //查詢範圍縮小到前半段 } } return -1; //查詢不成功,返回-1 } //分塊查詢 //index代表索引陣列,st2代表待查詢陣列,keytype代表要查詢的元素,m代表每塊大小 public static int blocksearch(int[] index,int[]st2,int keytype,int m){ int i=shunxusearch(index,keytype); //shunxunsearch函式返回值為帶查詢元素在第幾塊 System.out.println("在第"+i+"塊"); if(i>=0){ int j=m*i; //j為第i塊的第一個元素下標 int curlen=(i+1)*m; for(;j<curlen;j++){ if(st2[j]==keytype) return j; } } return -1; } public static int shunxusearch(int[]index,int keytype){ if(index[0]>keytype){ //如果第一塊中最大元素大於待查詢元素 return 0; //返回0.即待查詢元素在第0塊 } int i=1; while((index[i-1]<keytype)&&(index[i]>keytype)) return i; return -1; } public static void main(String args[]){ int st1[]={1,2,3,4,5,6,7,8,9,10}; System.out.println("順序查詢,輸入要查詢的關鍵字"); Scanner sc1=new Scanner(System.in); int keytype1=sc1.nextInt(); System.out.println("關鍵字在第"+seqsearch(st1,keytype1)+"個位置"); System.out.println("二分查詢,輸入要查詢的關鍵字"); Scanner sc2=new Scanner(System.in); int keytype2=sc2.nextInt(); System.out.println("關鍵字在第"+binarysearch(st1,keytype2)+"個位置"); int index[]={22,48,86}; int st2[]={22, 12, 13, 8, 9, 20, 33, 42, 44, 38, 24, 48, 60, 58, 74, 49, 86, 53}; System.out.println("分塊查詢"); System.out.println(blocksearch(index,st2,44,6)); } }
執行結果