排长度相同的字符串,由后往前根据字符对字符串分组
排序前:[1she2, 2sel3, 3seat, 1by2e, 3the2, 5she2, 4she7, 2sel1, 4are2, 2sur3] 排序后:[1by2e, 1she2, 2sel1, 2sel3, 2sur3, 3seat, 3the2, 4are2, 4she7, 5she2]
排长度不同的字符串,由前往后根据字符对字符串分组,递归对子字符串分组 排序前:[she, sells, the, hantao, daneng, dou, she, like, li, min, doudou, a, banana] 排序后:[a, banana, daneng, dou, doudou, hantao, li, like, min, sells, she, she, the]
import java.util.Arrays; /** * 字符串排序 * 1、低位优先(只能排序长度相同的字符串) * 2、高位优先(要特别注意到达字符串末尾的情况:将已经检查到末尾的字符串所在的子数组排在所有子数组的前面) * @author Administrator * */ public class sortString { private static int R = 256; //基于扩展的ASCII字符集 private static String[] tempArray;//临时数组 //低位优先(只能排序长度相同的字符串) private void lowPriorSortString(String[] sameLenString) { int numArray = sameLenString.length;//字符串数量 tempArray = new String[numArray];//临时数组 for( int i=sameLenString[0].length()-1;i>=0;i-- )//从低位开始根据每个字符排序 { int[] count = new int[R+1]; //根据相同字符计数 for( int j=0;j<numArray;j++ ) { count[sameLenString[j].charAt(i)+1]++; } //将频率换成索引 for( int j=0;j<R;j++ ) { count[j+1] += count[j]; } //将元素分类 for( int j=0;j<numArray;j++ ) { tempArray[count[sameLenString[j].charAt(i)]++] = sameLenString[j]; } //回写 for( int j=0;j<numArray;j++ ) { sameLenString[j] = tempArray[j]; } } } //高位优先 private void highPriorSortString(String[] differentLenString) { int numArray = differentLenString.length;//字符串数量 tempArray = new String[numArray];//临时数组 sort( differentLenString,0,numArray-1,0 ); } //若字符串已结束则返回-1 private int charAt( String s,int d ) { if( d<s.length() ) { return s.charAt(d); } else { return -1; } } //高位优先递归排序 private void sort( String[] differentLenString,int lo,int hi,int d ) { if( hi<=lo ) return; //递归出口 int[] count = new int[R+2]; //根据相同字符计数 for( int j=lo;j<=hi;j++ ) { count[charAt( differentLenString[j],d )+2]++; } //将频率换成索引 for( int j=0;j<R+1;j++ ) { count[j+1] += count[j]; } //将元素分类 for( int j=lo;j<=hi;j++ ) { tempArray[count[charAt( differentLenString[j],d )+1]++] = differentLenString[j]; } //回写 for( int j=lo;j<=hi;j++ ) { differentLenString[j] = tempArray[j-lo]; } //递归的以每个字符串为键进行排序 for( int j=0;j<R;j++ ) { sort( differentLenString,lo+count[j],lo+count[j+1]-1,d+1 ); } } public static void main(String[] args) { sortString ss = new sortString(); String[] sameLenString = { //相同长度的字符串 "1she2", "2sel3", "3seat", "1by2e", "3the2", "5she2", "4she7", "2sel1", "4are2", "2sur3" }; String[] differentLenString = { //不同长度的字符串 "she", "sells", "the", "hantao", "daneng", "dou", "she", "like", "li", "min", "doudou", "a", "banana" }; System.out.println("等长字符串排序前:"+Arrays.toString(sameLenString)); ss.lowPriorSortString(sameLenString);//低位优先(只能排序长度相同的字符串) System.out.println(" 低位优先排序后:"+Arrays.toString(sameLenString)); System.out.println("\r\n 非等长字符串:"+Arrays.toString(differentLenString)); ss.highPriorSortString(differentLenString);//低位优先(只能排序长度相同的字符串) System.out.println("高位优先排序后:"+Arrays.toString(differentLenString)); } }