I heard that in quicksort it is better to call recursion on a smaller subarray first. For example, if 5 was a pivot point, and the data is sorted to 4,1,3,5,7,6 , then it is better to sort the subarray 7,6 , because it contains two elements, where as 4,1,3 contains three .
The source of all knowledge provides pseudo code for quick sorting.
quicksort(A, i, k): if i < k: p := partition(A, i, k) quicksort(A, i, p - 1) quicksort(A, p + 1, k)
Thus, an algorithm that will implement off for recursion on a smaller array will look something like this:
quicksort(A, i, k): if i < k: p := partition(A, i, k) if(pi > kp) /*difference from start point to pivot is greater than difference from pivot to end point*/ quicksort(A, p + 1, k) quicksort(A, i, p - 1) else quicksort(A, i, p - 1) quicksort(A, p + 1, k)
I wrote code like this written in Java and it seems to be faster, but why? At first I thought it was due to tail recursion optimization, but then I realized that it was wrong, because Java does not support it.
Why sort code in a smaller subarray first? This article claims that it should be