2013-03-21 75 views
-4

我在这种类型中遇到了一些麻烦。它只会按顺序正确显示第一个文件。任何人看到我做错了什么?我一直试图找出几个小时,只是没有看到我做错了什么。选择用对象ArrayList排序

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 

} 
+0

调试存在使用。 – 2013-03-21 01:53:38

+0

请张贴一些样本输入和输出。还要更详细地描述问题。你为什么要实现排序而不使用'Collections.sort(fileList);'? – Jess 2013-03-21 01:56:14

回答

1

内循环应该是for(int i = 0; i <= last; i++),因为您从尚未排序的内容中选择最好的。在上一次你已经在外循环的前几次迭代中排序后的所有内容。

也,你不复位的max在每次迭代的价值,所以在内部for循环,写max = 0;

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