字符串排序
package javastudy; public class Test4 { public static void main(String[] args){ String s [] = {"dad","bood","bada","Admin","xxx","Good", "aete","cc","Ko","Beta","Could","Goodd","Gooda"}; String stemp = null ; //下面的是冒泡排序 for (int i = 0; i < s.length; i++) { for (int j = 0; j < s.length - i - 1; j++) { if (stringCmp(s[j], s[j + 1]) > 0) { stemp = s[j]; s[j] = s[j + 1]; s[j + 1] = stemp; } } } for (int i=0;i<s.length ;i++){ System.out.print(s[i]+" ") ; } } /** * A(97),a(65) * @param s1 * @param s2 * @return >0-->s1>s2 */ public static int stringCmp(String s1, String s2 ){ int nResult = s1.length() - s2.length() ;; int nLen = Math.min(s1.length(), s2.length()) ; int nCharOrder1, nCharOrder2; char aChar1 [] = s1.toCharArray(); char aChar2 [] = s2.toCharArray(); for (int i = 0; i < nLen; i++) { //如果在nLen内有char不一样(包括同一char,一个大写一个小写,和两个不同的char) if (aChar1[i] != aChar2[i]) { nCharOrder1 = aChar1[i] > 96 ? aChar1[i] - 96 : aChar1[i] - 64; nCharOrder2 = aChar2[i] > 96 ? aChar2[i] - 96 : aChar2[i] - 64; if (nCharOrder1 != nCharOrder2) {// 不同的char(这里不包括大小写,如A ,a) nResult = nCharOrder1 - nCharOrder2; break; } else { nResult = aChar1[i] - aChar2[i]; // 相同 的char时(A,a) break; } } //如果在nLen 内一直没有不同的char } return nResult ; } }
结果
Admin aete Beta bada bood Could cc dad Good Gooda Goodd Ko xxx