简体   繁体   中英

How to make a generic quicksort method run correctly with objects in an arraylist

I am trying to finish a program that uses a generic quicksort method to sort an arraylist of objects, I finally got rid of all the common errors I was familiar with but my program is still not sorting properly. I used a similar algorithm when I was sorting just Strings and it was not generic so I'm not sure where I went wrong. Please help! Here is the following quicksort code I have been working with:

private static <E> void doQuickSort(ArrayList <E> list, int start, int end)
{
    if(list == null || list.size() == 0)
        return;
    if(start >= end)
        return;

    int middle = start + (end - start) / 2;
    E pivot = (E) list.get(middle);

    int s = start, e = end;
    while (s <= e)
    {
        while(pivot.equals(list.get(s)))
        {
            s++;
        }

        while(pivot.equals(list.get(e)))
            e--;


    if(s <= e)
    {
        E temp = list.get(s);
        list.set(s,  list.get(e));
        list.set(e, temp);
        s++;
        e--;
    }


    if(start < e)
        doQuickSort(list, start, e);
    if(end > s)
        doQuickSort(list, s, end);
    }
}

Strings are Comparable so you can use compareTo with a String. When you made it generic, you did not specify that the generic elements have to be Comparable, and from your code you are no longer using compareTo. If you use equals instead of compareTo, you cannot determine which elements come before which other elements. As a result, you are not sorting anything.

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