庞果网-数组排序

来源:互联网 发布:邮箱搜索软件 编辑:程序博客网 时间:2024/06/03 02:27

题目详情本题来自caopengcs,只要你有兴趣,每个人都可以出题(出题入口在主页右侧边栏“贡献题目”->“我要发布”内),以下是题目详情:给定一个包含1-n的数列,我们通过交换任意两个元素给数列重新排序。求最少需要多少次交换,能把数组排成按1-n递增的顺序,其中,数组长度不超过100。例如:原数组是3,2,1, 我们只需要交换1和3就行了,交换次数为1,所以输出1。原数组是2,3,1,我们需要交换2和1,变成1,3,2,再交换3和2,变为1,2,3,总共需要的交换次数为2,所以输出2。

只想到最容易想到的方法,时间复杂度N^2:

   public static int  run(int []a) {         int times = 0;        int temp = 0;        int tempIndex = 0;        int len = a.length;        boolean flag = false;        for (int i = 0; i < len; i++) {            temp = a[i];            for (int j = i + 1; j < len; j++) {                if (a[i] > a[j]) {                    if (temp > a[j]) {                        tempIndex = j;                        temp = a[j];                        flag = true;                    }                }            }            if (flag) {                times++;                flag = false;                int swap = a[i];                a[i] = a[tempIndex];                a[tempIndex] = swap;            }        }        return times;    }

原创粉丝点击