空闲时,忽然想如何实现根据字母进行排序,此文章只不过是抛砖引玉的作用,如果有好的算法,欢迎指教。
package com.sort;
public class AlphaticalOrder {
/**
* @param args
*/
public static void main(String[] args) {
sortString(new String[]{"which","Get","What","Mother","Don","Doney"});
}
/**
* 判断两个元素是否应该交换
* @param strA
* @param strB
* @return
*/
private static boolean isSwitch(String strA,String strB){
int aLen = strA.length();
int bLen = strB.length();
int len = aLen>bLen?bLen:aLen;
con:for(int i=0;i<len;i++){
int a = strA.charAt(i);
int b = strB.charAt(i);
if(a>b)
return true;
else if(a<b)
return false;
continue con;
}
return false;
}
/**
* 冒泡算法使大值靠后小值靠前
* @param strArr
*/
private static void sortString(String[] strArr){
for(int i=0;i<strArr.length-1;i++){
for(int j=i+1;j<strArr.length;j++){
if(isSwitch(strArr[i],strArr[j])){
String temp = strArr[i];
strArr[i] = strArr[j];
strArr[j] = temp;
}
}
}
for(int z=0;z<strArr.length;z++){
System.out.print(strArr[z]+" ");
}
}
}