简体   繁体   中英

Recursive Quicksort for a LinkedList

I've been trying to implement a Recursive Quicksort into my algorithm which makes use of LinkedList. However when I run the method, it seems to go on forever even for a small list (of 10 elements), I've been waiting for the method to stop for about 10 minutes.

This is the code in question

public static void QuickSort(LinkedList<Contacto> Lista, int ini, int fin){
    Contacto pivote, aux;
    int i, j, comp;


    if (ini<fin){
        pivote = Lista.get(ini);
        i=ini+1;
        j=fin;

        while (i<j){
            while(i<fin && (comp=Lista.get(i).get_name().compareTo(pivote.get_name()))<=0 )
                i++;

            while((comp=Lista.get(i).get_name().compareTo(pivote.get_name()))>0 )
                j--;

            if(i<j){
                aux = Lista.get(i);
                Lista.set(i, Lista.get(j));
                Lista.set(j, aux);
                }
            }
        aux=Lista.get(j);
        Lista.set(j,pivote);
        Lista.set(ini,aux);
        QuickSort(Lista,ini,j-1);
        QuickSort(Lista,j+1,fin);
    }
}

Thanks for your help!

As is noted in the comments, the fact that it's taking ten minutes to sort a list of ten items is due to a bug somewhere, and I recommend you insert some breakpoints/ println() statements to get a sense for how your method is proceeding (one at the top of each of your conditionals should be sufficient to show you where it's getting hung up).

That said, inefficiency with very short lists is a known problem with the quicksort algorithm - and, if you think about how the algorithm works, you can see why it's an inherent one. (I can expound on this, but you'll be better off if you figure out why yourself).

A common solution to this issue is having a cutoff : When the size of the list becomes smaller than the cutoff size, switch to a simple insertion sort to finish the job. There is a good discussion about this here , and a very good example implementation here .

Note the first few lines of the quicksort() method in that example:

private static void quicksort(Comparable [] a, int left, int right) {
    final int CUTOFF = 3;
    if (right-left+1 < CUTOFF) { // if less than three elements remain: 
         insertionSort(a,left,right);
    else { //quicksort...

(note: that first link comes from the booksite for Algorithms, 4th edition , written by some folks at Princeton. I can't recommend that site highly enough as you're reasoning through the fundamental algorithms)

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