简体   繁体   English

我实现QuickSort的问题

[英]Problem with my implementation of QuickSort

I'm trying to sort files by their extensions (and if the extensions are the same so by the file's name) using my own implementation of quickSort. 我正在尝试使用我自己的quickSort实现按照扩展名对文件进行排序(如果扩展名是相同的文件名)。

So when I'm sorting a small group of files it works fine but when I'm using a big group, from some reason some files are disappearing from the result list. 因此,当我对一小组文件进行排序时,它可以正常工作,但是当我使用一个大组时,某些文件会从结果列表中消失。 I can't find the cause for that. 我无法找到原因。 (the sorting itself works as expected... the problem is only with the missing files). (排序本身按预期工作......问题仅在于丢失的文件)。 Any ideas? 有任何想法吗?

public static ArrayList<Extention> quickSort(ArrayList<Extention> list)
{
    if (list.size() <= 1)
        return list; // Already sorted

    ArrayList<Extention> sorted = new ArrayList<>();
    ArrayList<Extention> lesser = new ArrayList<>();
    ArrayList<Extention> greater = new ArrayList<>();
    Extention pivot = list.get(list.size()-1);
    for (int i = 0; i < list.size()-1; i++)
    {
        //int order = list.get(i).compareTo(pivot);
        if (list.get(i).getExtention().compareTo(pivot.getExtention()) < 0)
            lesser.add(list.get(i));
        else if (list.get(i).getExtention().compareTo(pivot.getExtention()) == 0){
            if (list.get(i).getFileName().compareTo(pivot.getFileName()) < 0){
                lesser.add(list.get(i));
            }
        }
        else{
            greater.add(list.get(i));}
    }

    lesser = quickSort(lesser);
    greater = quickSort(greater);

    lesser.add(pivot);
    lesser.addAll(greater);
    sorted = lesser;

    return sorted;
}

It looks like you're missing an else in this section: 看起来你错过了本节中的else内容:

  ... else if (list.get(i).getExtention().compareTo(pivot.getExtention()) == 0){ if (list.get(i).getFileName().compareTo(pivot.getFileName()) < 0){ lesser.add(list.get(i)); } } ... 

It should be 它应该是

  ... else if (list.get(i).getExtention().compareTo(pivot.getExtention()) == 0){ if (list.get(i).getFileName().compareTo(pivot.getFileName()) < 0){ lesser.add(list.get(i)); } else { greater.add(list.get(i)); } } ... 

Also note that since you choose the first item as pivot, you should start the loop at 1 and not zero (in order not to insert the pivot twice) 另请注意,由于您选择第一个项目作为数据透视表,因此您应该将循环设置为1而不是零(为了不插入两次枢轴)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM