选择使用ArrayList对象排序

时间:2013-03-21 01:48:32

标签: java sorting arraylist selection

我遇到这种麻烦。它只会按顺序正确显示第一个文件。有谁看到我做错了什么?我一直试图弄清楚好几个小时,只是看不出我做错了什么。

public void sort() { 

    int i; //loop control
    int last; //last position in the arraylist
    int max; //position where last alphabetical filename is found

    max = 0; //largest position so far is first, since i haven't checked

    //I thought i should start at the end and work my way down
    for(last = fileList.size()-1; last >= 0; last--) {

        for(i = 0; i < fileList.size(); i++) {
            if(fileList.get(max).getFileName().compareTo(fileList.get(i).getFileName()) > 0)
                max = i;
        }

        //swap pixfile in last position with the last alphabetical
        Pixfile tempPix = fileList.get(last);
        fileList.set(last, fileList.get(max));
        fileList.set(max, tempPix);
        //i thought i would repeat until last = 0 and the arraylist is sorted
    }//end for

}

1 个答案:

答案 0 :(得分:1)

内部for循环应该是for(int i = 0; i <= last; i++)因为你从尚未排序的东西中选择最好的。最后你已经在外部循环的前一次迭代中进行了排序。

另外,你没有在每次迭代中重置max的值,所以在内部for循环之前,写max = 0;

另外,如果你懒得编写排序算法,你可以随时使用Arrays.sort()Collections.sort()

相关问题