Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swap method for quicksort in java

Could anyone help me figure out this swap method that is a part of a larger quick sort program? It is supposed to take an array and two integers and swap the index positions indicated by the integers.

private static <T extends Comparable<T>> int partition(T[] table, int first, int last) {
    T pivot = table[first];
    int up = first;
    int down = last;

    do {
        while ((up < last) && (pivot.compareTo(table[up]) >= 0)) {
            up++;
        }
        while (pivot.compareTo(table[down]) < 0) {
            down--;
        }
        if (up < down) {
            swap(table, up, down);
        } 
    }

    while (up < down);
    swap(table, first, down);
    return down;
}

The swap method is currently undefined and I am not sure how to get it working. I have tried writing the method:

void swap(T[] array, int a, int b) {
    T temp = array[a];
    array[a] = array[b];
    array[b] = temp;
}

However I keep getting the error that T cannot resolve to a type. But when I try to change the type to int the method doesn't work where it is called above.

like image 519
Teej Avatar asked Apr 23 '26 10:04

Teej


1 Answers

You need to add the generic type <T> to your swap method. Something like

static <T> void swap(T[] array, int a, int b) {
    T temp = array[a];
    array[a] = array[b];
    array[b] = temp;
}
like image 152
Elliott Frisch Avatar answered Apr 25 '26 23:04

Elliott Frisch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!