字串陣列二分查詢(僅限字母組成的字串)
阿新 • • 發佈:2021-07-13
1 package algorithm; 2 3 import java.util.Arrays; 4 5 public class HalfSearch { 6 public static void main(String[] args) { 7 String[] arr= {"tomato","orange","peach","pear","apple","banana","lemen","pe","p"}; 8 String query="orange";//需要查詢的字串 9 sort(arr,query); 10} 11 public static void sort(String[] arr,String query) { 12 //氣泡排序(字串陣列) 13 for(int i=0;i<arr.length-1;i++) { 14 for(int j=i+1;j<arr.length;j++) { 15 String temp; 16 //如果首字母大小相同,比較長度,小的在前 17 if(arr[i].charAt(0)==arr[j].charAt(0)) { 18 if(arr[i].equals(arr[j])) { 19 continue;//結束當次迴圈 20 } 21 if(arr[i].length()>arr[j].length()) { 22 temp=arr[j]; 23arr[j]=arr[i]; 24 arr[i]=temp; 25 continue;//結束當次迴圈 26 } 27 int len; 28 if(arr[i].length()<=arr[j].length()) { 29 len=arr[i].length(); 30 }else { 31 len=arr[j].length(); 32 } 33 //比較首字母后面的每一個進行排序 34 for(int k=1;k<len;k++) { 35 if(arr[i].charAt(k)>arr[j].charAt(k)) { 36 temp=arr[j]; 37 arr[j]=arr[i]; 38 arr[i]=temp; 39 continue; 40 } 41 } 42 }else { 43 //首字母不相等常規排序交換 44 if(arr[i].charAt(0)>arr[j].charAt(0)) { 45 temp=arr[j]; 46 arr[j]=arr[i]; 47 arr[i]=temp; 48 } 49 } 50 } 51 } 52 System.out.println(Arrays.toString(arr)); 53 54 //進行二分查詢 55 int left=0,right=arr.length-1; 56 int middle=(left+right)/2; 57 while(!arr[middle].equals(query)) { 58 System.out.println(arr[left]+","+arr[middle]+","+arr[right]); 59 if(arr[middle].charAt(0)>query.charAt(0)) { 60 right=middle; 61 }else if(arr[middle].charAt(0)<query.charAt(0)){ 62 left=middle; 63 }else{ 64 if(arr[middle].length()<query.length()) { 65 left=middle; 66 }else if(arr[middle].length()>query.length()){ 67 right=middle; 68 }else { 69 break; 70 } 71 } 72 middle=(left+right)/2;79 } 80 System.out.println(query+"的位置->"+middle); 81 } 82 }
漢字字串排序因為有封裝類,所以比較簡單
1 package algorithm; 2 3 import java.text.Collator; 4 import java.util.Arrays; 5 6 public class Test { 7 public static void main(String[] args) { 8 //漢字比較大小 9 Collator collator= Collator.getInstance(java.util.Locale.CHINA); 10 String[] arr= {"中a","美b","俄c","英d","日e"}; 11 for(int i=0;i<arr.length-1;i++) { 12 for(int j=i+1;j<arr.length;j++) { 13 String temp; 14 if(collator.compare(arr[i],arr[j])>0) { 15 temp=arr[j]; 16 arr[j]=arr[i]; 17 arr[i]=temp; 18 } 19 } 20 } 21 System.out.println(Arrays.toString(arr)); 22 23 } 24 }