The goal is to have a function that can sort a series of all object types that implement the comparable interface. I'm not trying to improve the performance of the sort. I'm only trying to optimize my use of generics.
I currently use T extends whatever
and T[]
, however I was also considering to use T extends whatever
and ArrayList<T>
. Is one more preferable over the other or are both approaches just trash? If you have other remarks please tell me I'm here to learn :)
public static void main( String[] args )
{
String[] stringList = {"hello", "this", "is", "a", "test", "ab", "aaa","aba"};
Quicksort.sort(stringList, 0, stringList.length - 1);
System.out.println( Arrays.toString(stringList));
}
public class Quicksort{
private static <T extends Comparable<T>> int partitioning(T[] arr, int start, int end) {
T pivot = arr[end];
int balancePoint = start; // everything that's smaller to the left of this, the rest to the right
for (int i = start; i < end; i++) {
if(arr[i].compareTo(pivot)<=0) {
Arrayswap.genericArraySwap(arr, i, balancePoint);
balancePoint++;
}
}
Arrayswap.genericArraySwap(arr, end, balancePoint);
return balancePoint;
}
public static <T extends Comparable<T>> void sort(T[]a, int i, int j) {
if (i>=j) {
return;
}
int pivot = partitioning(a, i, j);
sort(a, i, pivot-1);
sort(a, pivot+1, j);
}
}
main(
and before the closing)
- not consistent ;) \$\endgroup\$