冒泡排序对字符串数组排序

给定一个字符串排序:以字母为准,比如:a < B或者b .同字母的情况,小写字母大于大写字母,比如:A < a

private static void testCompareString() {
        String[] aSource = {"dad", "bood", "bada", "Admin", "   ", "Good", "aste", "cc", "Ko", "Beta", "Could" };


        //使用do-while
        boolean isChanged;
        int nMaxIndex = aSource.length - 1;
        String temp = null;
        do {
            isChanged = false;

            for (int i = 0; i < nMaxIndex; i++) {
                if (StringCmp(aSource[i], aSource[i+1]) > 0) {
                    temp = aSource[i];
                    aSource[i] = aSource[i+1];
                    aSource[i+1] = temp;
                    isChanged = true;
                }
            }
            nMaxIndex--;//大的沉底,小的向上浮。开始是10-->0
        }while(isChanged);

        //方式2:使用for进行
        /*for (int i = 0; i < aSource.length - 1; i++) {
            for (int j = 0; j < aSource.length - i - 1; j++) {
                if (StringCmp(aSource[j], aSource[j+1]) > 0) {
                    temp = aSource[j];
                    aSource[j] = aSource[j+1];
                    aSource[j+1] = temp;
                }
            }
        }*/


        System.out.println("========================");
        for (int i = 0; i < aSource.length; i++) {
            System.out.println(aSource[i]);
        }
    }
    private static int StringCmp(String s1, String s2) {
        int diffNum = s1.length() - s2.length();
        int minLen = Math.min(s1.length(), s2.length());

        int order1,order2;


        char[] nChar1 = s1.toCharArray();
        char[] nChar2 = s2.toCharArray();

        for (int i = 0; i < minLen; i++) {
            if (nChar1[i] != nChar2[i]) {
                order1 = (nChar1[i] - 96) > 0? nChar1[i] - 96 : (nChar1[i] - 64);
                order2 = (nChar2[i] - 96) > 0? nChar2[i] - 96 : (nChar2[i] - 64);

                if(order1 != order2) {
                    diffNum = order1 - order2;
                    break;
                } else {
                    diffNum = nChar1[i] - nChar2[i];
                    break;
                }
            }
        }

        return diffNum;
    }

猜你喜欢

转载自blog.csdn.net/u010503822/article/details/78751273
今日推荐