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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With