Quicksort - Implementation Improvements

This section provides a tutorial on how to improve the performance of the Quicksort implementation in different areas.

There are ways to improve my first implementation of the Quicksort algorithm.

First, we can improve the division process by replacing the one-way loop with a two-way loop to reduce the number of swapping operations.

Another area that can be improved is when sections are being divided smaller enough, like number of elements less than 3, or 4. Instead of dividing them further, we can sort them directly.

Here is my improved version of Quicksort:

```/**
* HyArrays.java
* This class contains sorting methods similar to java.util.Arrays.
* All sorting methods should have a signature of
* %Sort(Object[] a, int fromIndex, int toIndex)
* where "fromIndex" is inclusive, and "toIndex" is exclusive.
* Copyright (c) 2011 by Dr. Herong Yang, herongyang.com
*/
public class HyArrays {
public static void quickSortImproved(Object[] a, int fromIndex,
int toIndex) {
Object d;
if (toIndex-fromIndex<=1) {
return;
} else if (toIndex-fromIndex==2) {
if (((Comparable)a[fromIndex]).compareTo(a[toIndex-1])>0) {
d = a[toIndex-1];
a[toIndex-1] = a[fromIndex];
a[fromIndex] = d;
}
} else {
int iLeft = fromIndex + 1;
int iRight = toIndex - 1;
Comparable p = (Comparable) a[fromIndex];
while (iLeft<iRight) {
while (iLeft<toIndex-1 && p.compareTo(a[iLeft])>=0) {
iLeft++;
}
while (iRight>fromIndex+1 && p.compareTo(a[iRight])<=0) {
iRight--;
}
if (iLeft>=iRight) break;
d = a[iRight];
a[iRight] = a[iLeft];
a[iLeft] = d;
}
if (iLeft>fromIndex+1) {
d = a[iRight];
a[iRight] = a[fromIndex];
a[fromIndex] = d;
}
if (iLeft==iRight && iRight==toIndex) {
quickSortImproved(a, fromIndex, iRight);
} else if (iLeft==iRight && iRight==fromIndex) {
quickSortImproved(a, iLeft, toIndex);
} else {
quickSortImproved(a, fromIndex, iRight);
quickSortImproved(a, iLeft, toIndex);
}
}
}
}
```

Here is the result of this version:

```Array size: 10000
Average sorting time: 16 milliseconds
Number of tests: 1000
Performance: 1.6 O(N) nanoseconds
Performance: 0.12041199826559247 O(N*Log2(N)) nanoseconds
Performance: 1.6E-4 O(N*N) nanoseconds

Array size: 20000
Average sorting time: 40 milliseconds
Number of tests: 1000
Performance: 2.0 O(N) nanoseconds
Performance: 0.13998042141880435 O(N*Log2(N)) nanoseconds
Performance: 1.0E-4 O(N*N) nanoseconds

Array size: 30000
Average sorting time: 70 milliseconds
Number of tests: 1000
Performance: 2.3333333333333335 O(N) nanoseconds
Performance: 0.15688726823636978 O(N*Log2(N)) nanoseconds
Performance: 7.777777777777778E-5 O(N*N) nanoseconds
```

The results is interesting. The improvement is significant. The performance is much better than my initial version. It actually performs better than the JDK implementation when N = 10000 and 20000.

Last update: 2011.

Table of Contents