码迷,mamicode.com
首页 > 编程语言 > 详细

字符串排序

时间:2015-07-19 16:20:26      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:

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 

字符串排序

标签:

原文地址:http://www.cnblogs.com/chuiyuan/p/4658681.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!