我怎么能进行排序,而无需使用collections.sort()一个ArrayList? [英] How can I sort an arraylist without using collections.sort()?

查看:133
本文介绍了我怎么能进行排序,而无需使用collections.sort()一个ArrayList?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找了一段时间的一种方式,而无需使用collections.sort作为我自己的逻辑来排序的ArrayList是有缺陷的,我一直有一个很大的麻烦。

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做才能彻底排序的ArrayList。

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.

下面是我的code:

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.

推荐答案

我假设你想下面的算法:找分钟在阵列的​​其余部分,与当前的元素交换就开始与第一,考虑的其他是数组增加+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.

您应该更新code是这样的:

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);
    }
}

您有发现最小的,然后交换物品的错误。请注意,code可以在许多方面加以改进(我试图保持编码尽可能的让我们说的方式),如掉期(互换整数引用),做冒泡像另一个答案建议(相同的算法,但更简单的实现),使用 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()一个ArrayList?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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