如何在不使用 collections.sort() 的情况下对数组列表进行排序? [英] How can I sort an arraylist without using collections.sort()?

查看:33
本文介绍了如何在不使用 collections.sort() 的情况下对数组列表进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找一种在不使用 collections.sort 的情况下对数组列表进行排序的方法,因为我自己的逻辑存在缺陷并且遇到了很多麻烦.

I have been looking for a while for a way to sort an arraylist without using collections.sort as my own logic is flawed and I have been having a lot of trouble.

我需要以一种可以使用我创建的方法对其进行排序,该方法基本上执行 collections.swap 所做的以便对数组列表进行完全排序.

I need to sort it in a way that I can use a method I created that basically does what collections.swap does in order to completely sort an arraylist.

这是我的代码:

public static void mySort(ArrayList<Double> sort){

    int min = 0;
    int i;
    int j = 0;
        for(i = 0; i < sort.size() - 1; i++) {
            min = i;
            mySwap(sort, j ,min);

            for(j = 0; j < sort.size() -1;j++){
                if(j < min ){
                    min = j;
                }
            }
    }
}

public static void mySwap(ArrayList<Double> a, int x, int y){

    double temp = a.get(x);
    a.set(x,a.get(y));
    a.set(y,temp);
}

我在这方面遇到了很多麻烦.对不起,如果这是一个损害社区的问题.

I have been having a lot of trouble of with this. Sorry if it is a question is that harming the community.

推荐答案

我假设您想要以下算法:在数组的其余部分中找到 min,将其与以 first 开头的当前元素交换,重新考虑 rest 是增加 +1 索引的数组开始.

I assume you want the following algorithm: find min in the rest of the array, swap it with current element starting with first, reconsider rest to be array starting of increased +1 index.

你应该像这样更新你的代码:

You should update your code like this:

public static void swap(List<Integer> sort, int i, int j) {
    int tmp = sort.get(i);
    sort.set(i, sort.get(j));
    sort.set(j, tmp);
}

public static void doSort(List<Integer> sort) {
    int min;
    for (int i = 0; i < sort.size(); ++i) {
        //find minimum in the rest of array
        min = i;
        for (int j = i + 1; j < sort.size(); ++j) {
            if (sort.get(j) < sort.get(min)) {
                min = j;
            }
        }

        //do swap
        swap(sort, i, min);
    }
}

您在查找最小值然后交换项目时遇到了错误.请注意,可以通过多种方式改进代码(我尝试尽可能保持您的假设编码方式),例如在 swap() 中交换整数引用,执行 BubbleSort 就像另一个答案建议的一样(相同的算法但更简单的实现),使用 O(n * log(n)) 复杂度算法,依此类推.

You have a bug with finding minimum and then swapping items. Please note that the code can be improved in many ways (I tried to maintain your let's say way of coding as possible), such as swapping integer references in swap(), doing BubbleSort like another answer suggests (same algorithm but simpler implementation), using O(n * log(n)) complexity algorithm, and so on.

这篇关于如何在不使用 collections.sort() 的情况下对数组列表进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆