I've been comparing the performance of recursive Quicksort and iterative QuickSort and it seems that my recursive QuickSort is consistently faster than my iterative version. I'm just wondering if there is any reason why the recursive version would be faster? as from my understanding, the iterative version should perform faster as it avoids the cost of recursive calls.
recursive QuickSort implementation
int Pivot = 1;
QuickSort cleanRun = new QuickSort(runArray, Pivot);
int last = runArray.length - 1;
long start = System.nanoTime();
cleanRun.quickSort(0, last);
long end = System.nanoTime();
Recursive Quicksort Class
public class QuickSort extends SortingAlgorithm {
public QuickSort(int[] l, int pivot) {
super(l);
}
public int[] getL() {
return l;
}
public void quickSort(int first, int last) {
int splitPoint;
if (first < last) {
splitPoint = split(first, last);
quickSort(first, splitPoint - 1);
quickSort(splitPoint + 1, last);
}
}
private int split(int first, int last) {
int splitPoint, unknown;
int x;
int temp;
int temp2;
x = l[first];
splitPoint = first;
for (unknown = first + 1; unknown <= last; unknown++) {
if (l[unknown] < x) {
splitPoint = splitPoint + 1;
//interchange(splitPoint, unknown);
temp = l[splitPoint];
l[splitPoint] = l[unknown];
l[unknown] = temp;
}
}
temp = l[first];
l[first] = l[splitPoint];
l[splitPoint] = temp;
return splitPoint;
}
}
Iterative Quicksort Implementation
QuickSortStack cleanRun = new QuickSortStack(runArray);
int last = runArray.length - 1;
long start = System.nanoTime();
cleanRun.explicitStackingQuicksortCustomPivot(runArray);
long end = System.nanoTime();
Iterative Quicksort Class
public class QuickSortStack extends SortingAlgorithm {
public QuickSortStack(int[] l) {
super(l);
}
public int[] getL() {
return l;
}
/**
*
* @param l
*/
public void explicitStackingQuicksortCustomPivot(int l[]){
//these are the indexes
int first, last, splitPoint;
Stack stack = new Stack();
stack.push(0);
last = l.length-1;
stack.push(last);
while(!stack.empty())
{
last = (int) stack.pop();
first = (int) stack.pop();
while(first < last){
splitPoint = split2(first, last);
stack.push (splitPoint+1);
stack.push(last);
last = splitPoint - 1;
}
}
}
/**
*
* @param first
* @param last
* @return
*/
private int split2(int first, int last) {
int splitPoint, unknown;
int x;
int temp;
x = l[first];
splitPoint = first;
for (unknown = first + 1; unknown <= last; unknown++) {
if (l[unknown] < x) {
splitPoint = splitPoint + 1;
//interchange(splitPoint, unknown);
temp = l[splitPoint];
l[splitPoint] = l[unknown];
l[unknown] = temp;
}
}
temp = l[first];
l[first] = l[splitPoint];
l[splitPoint] = temp;
return splitPoint;
}
}