一数组 {'f','F','K','A','a','j','z'}
要求排序 为 {'A','a','F','f','j','K','z'}
发个个人认为比较好的方案
- java code
-
import java.util.Arrays;
import java.util.Comparator;
public class SortTest
{
public static void main(String args[])
{
char[] chs = {'f', 'F', 'K', 'A', 'a', 'j', 'z'};
chs = sortChars(chs, false);
for(char c: chs)
{
System.out.println(c);
}
}
/**
* 对给定的字符数组进行字典排序
* @param chs 目标字符数组
* @param upperFisrt 大写字母是否在前
* @return 排序后的字符数组
*/
public static char[] sortChars(char[] chs, final boolean upperFisrt)
{
Character[] srcArray = new Character[chs.length];
char[] retArray = new char[chs.length];
int index = 0;
for(char ch: chs)
{
srcArray[index++] = ch;
}
Arrays.sort(srcArray, new Comparator<Character>()
{
public int compare(Character c1, Character c2)
{
char ch1 = Character.toUpperCase(c1);
char ch2 = Character.toUpperCase(c2);
if(ch1 == ch2)
{
int tempRet = c1.charValue() - c2.charValue();
return upperFisrt? tempRet: -tempRet;
}
else
{
return ch1 - ch2;
}
}
});
index = 0;
for(char ch: srcArray)
{
retArray[index++] = ch;
}
return retArray;
}
}