Generic quicksort method and its testing program.
public class GenericQuickSort {
public static void main( String [] args) {
String [] strings = {"bananas", "oranges", "grapes", "mango",
"lemons", "pineapples", "apples", "kiwi",
"watermelons", "tangerines"};
quickSort(strings);
print(strings);
}
public static void print(Object [] array) {
for (int i = 0; i < array.length; ++i) {
System.out.println(array[i]);
}
}
public static void quickSort(Comparable [] array) {
quickSortRec(array, 0, array.length - 1);
}
public static void quickSortRec(Comparable [] array, int first, int last) {
// System.out.println(first + " , " + last);
// print(array);
if (first >= last ) return;
Comparable pivot = array[last];
// partition the array with this pivot
int i = first;
for (int j = first; j < last; ++j) {
if (array[j].compareTo(pivot) < 0) {
Comparable a = array[i];
array[i] = array[j];
array[j] = a;
i++;
}
}
Comparable a = array[i];
array[i] = array[last];
array[last] = a;
quickSortRec(array,first,i-1);
quickSortRec(array,i+1,last);
}
}
This is an example from CSci 2101 course.