1. 程式人生 > >桶排序和基數排序 Java

桶排序和基數排序 Java

複製程式碼
public class RadixSort_Letter{
     public static void main(String[] args){
          //宣告要排序的陣列
          String[] a = {"ac","ee","ef","b","z","f","ep","gaaa","azh","az","r"};
          //呼叫基數排序函式
          sort(a,4);
          //輸出排序後的陣列
          for(int i = a.length - 1;i >= 0;i--){
               System.out.print(a[i] + " ");
          }
     }

     //
/基數排序函式 //a是要排序的陣列 //m表示陣列元素最高位數,如我們排序的陣列中位數最高的元素為gaaa,有4位 public static void sort(String[] a,int m){ int n = 0; //27表示每一位字元分成27類,其中1~26對應'a'~'z' //第0位專門用來存放沒有高位字元的陣列元素,如在比較第二位字元時,b,z,f等沒有第二位字元的元素就存在temp[0]中 //相對應的,ac存在temp[1]中,ef存在temp[5]中 String[][] temp = new
String[27][a.length]; int[] order = new int[27]; while(n < m){ //這裡宣告String型別的陣列b,將陣列a中的每個元素倒序,然後放入陣列b //如a[0]="abc",則b[0]="cba" //之所以這樣做,是為了解決下面呼叫charAt方法時索引的問題,腦子太笨,沒想到更好的方法 String[] b = new String[a.length]; for
(int i = 0;i < a.length;i++){ if(a[i].length() > 1){ StringBuffer sb = new StringBuffer(a[i]); sb.reverse(); b[i] = new String(sb); }else{ b[i] = a[i]; } } for(int i = 0;i < a.length;i++){ if(a[i].length() > n){ int lsd = b[i].charAt(n) - 'a' + 1; temp[lsd][order[lsd]] = a[i]; order[lsd]++; }else{ temp[0][order[0]] = a[i]; order[0]++; } } int k = 0; for(int i = 0;i < 27;i++){ for(int j = 0;j < order[i];j++){ a[k] = temp[i][j]; k++; } order[i] = 0; } n++; } } }
複製程式碼轉自:http://www.cnblogs.com/bigfatxixi/p/3597004.html?utm_source=tuicool&utm_medium=referral