Skip to main content
2 of 6
deleted 468 characters in body
Celeritas
  • 911
  • 4
  • 14
  • 22

Tail recursive sort

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?

Celeritas
  • 911
  • 4
  • 14
  • 22