十一届蓝桥杯Java省赛 排序

public class Main {
    public static void main(String[] args) {
        /*思路,逆序字符串,计算一下即可
           11个字母
           nmlkjihgfedcba (13+0)*14/2 = 13*7 = 91
           onmlkjihgfedcba 14*15/2 = 7*15 = 105
           jonmlkihgfedcba 100次交换
         */
        //验证
        char[] arr= {'j','o','n','m','l','k','i','h','g','f','e','d','c','b','a'};
        int len = arr.length;
        int cnt = 0;
        boolean isSwap = false;
        for (int i = 0; i < len-1; i++) {
            isSwap = false;
            for (int j = 0; j < len - i - 1; j++) {
                if(arr[j] > arr[j+1]){
                    char tmp = arr[j];
                    arr[j] = arr[j+1];
                    arr[j+1] = tmp;
                    isSwap = true;
                    cnt++;
                }
            }
            if (!isSwap) break;
        }

        System.out.println(Arrays.toString(arr));
        System.out.println(cnt);
    }
}

你可能感兴趣的:(蓝桥杯)