题目:将a、s、d、A、f、h、F 排序为:A、a、d、F、f、h、s
方法一:
public static void main(String[] args) { // TODO Auto-generated method stub String a[]={"a","s","d","A","f","h","F"}; Comparator c=new Comparator(){ public int compare(Object el1, Object el2){ String key1=el1.toString().toLowerCase() +"_"+el1.toString(); String key2=el2.toString().toLowerCase() +"_"+el2.toString(); return key1.compareTo(key2); } }; Arrays.sort(a, c); for(int i=0;i<a.length;i++){ //A、a、d、F、f、h、s System.out.print(" "+a[i]); } }
方法二:
写下我的思路吧: 1)分析 a的ASCII码(97)和 A的ASCII码(65) 相差32,我们明白所有大小写字符的ASCII码都相差32 2)大写字母的ASCII码+31.5 必然比它的小写字母ASCII码还要小0.5 3)考虑大写字母(Z)的ASCII码为 90,ASCII90就是区分 大小写的标志。 现在我们开始分析:字符串 a s d A f h F 97 115 100 65 102 104 70 我们将小于90的字符串都加31.5 97 115 100 96.5 102 104 101.5 我们再进行冒泡排序,得到: 96.5 97 100 101.5 102 104 115 即: A a d F f h s import java.util.*; public class Test { public static void main(String[] args) { Character [] c={'a','s','d','A','f','h','F'}; //冒泡排序 for(int i=0;i<c.length;i++){ for(int j=i+1;j<c.length;j++){ Double c2asciiF=(c[i].hashCode()<=90?c[i].hashCode()+31.5:c[i].hashCode()); Double c2asciiL=(c[j].hashCode()<=90?c[j].hashCode()+31.5:c[j].hashCode()); if(c2asciiF>c2asciiL){ Character tmp=c[i]; c[i]=c[j]; c[j]=tmp; } } } //循环打印 for(int i=0;i<c.length;i++){ System.out.println(c[i]); } } }
原帖地址:http://topic.csdn.net/u/20091227/18/be16f8d4-0d72-48cf-aa07-a7651cd39578.html?60275
方法一和方法二分别为帖子中的第4、20楼。