I've heard of this implementation of quick sort (in pseudocode):
TAIL-RECURSIVE-QUICKSORT(A, p, r)
while p < r
q = PARTITION(A, p, r)
if q < (p + (r-p)/2)
TAIL-RECURSIVE-QUICKSORT(A, p, q-1)
p = q+1
else
TAIL-RECURSIVE-QUICKSORT(A, q+1, p)
r = q-1
Here it is partially implemented.
private static void quickSort(int[] arr, int lo, int hi){
if(lo >= hi) return;
int p = partition(arr, lo, hi);
// modified to choose small partition first
if((p - lo )<=(hi-p)){
System.out.println(String.format("Sorting left first %d %d %d",lo,p,hi)) ;
quickSort(arr, lo, p);
quickSort(arr, p+1, hi);
}else {
System.out.println(String.format("Sorting right first %d %d %d",lo,p,hi));
quickSort(arr, p+1, hi);
quickSort(arr, lo, p);
}
}
Can it be made any faster? FWIW I profiled the above code against regular (recursive) quicksort and it was usually faster (tested on randomly generated arrays).
Here is partition and a method for swapping
private static int partition(int[] a, int p, int r) {
int x = a[p];
int i = p-1 ;
int j = r+1 ;
while (true) {
i++;
while ( i< r && a[i] < x)
i++;
j--;
while (j>p && a[j] > x)
j--;
if (i < j)
swap(a, i, j);
else
return j;
}
}
private static void swap(int[] a, int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}