简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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