I run Quicksort 10 times, and get the average mean time.
I do the same thing for Qicksort/Insertion sort combination, and it seems to be slower than just quicksort.
Here’s the part of the code where I call InsertionSort
public static <T extends Comparable<? super T>> void OptQSort2 (T[] data, int min, int max) {
int indexofpartition;
if(max - min > 0) {
if( (max - min) <= 10) {
// Use InsertionSort now
InsertionSort.sort(data);
return;
} else {
indexofpartition = findPartition(data, min, max);
OptQSort2(data, min, indexofpartition - 1);
OptQSort2(data, indexofpartition + 1, max);
}
}
}
And the regular Quicksort is just the same as the above snippet, but without the if condition that calls InsertionSort.
FindPartition is as follows:
public static <T extends Comparable<? super T>> int findPartition(T[] data, int min, int max) {
int left, right;
T temp, partitionelement;
int middle = (min + max)/2;
partitionelement = data[middle];
left = min;
right = max;
while(left < right) {
while(data[left].compareTo(partitionelement) <= 0 && left < right)
left++;
while(data[right].compareTo(partitionelement) > 0)
right--;
if(left < right) {
temp = data[left];
data[left] = data[right];
data[right] = temp;
}
}
The mean time for just Quicksort and OptSort2(which uses insertion sort) are
Sorted using QuickSort in: 3858841
Sorted using OptQSort2 in: 34359610
Any ideas why? Does the size of the sequence matter? I am using a 1000 element Integer[] array for this
In
OptQSort2, for small partitions, you have the following function call:Is this supposed to insertion sort the small partition? It looks like you are insertion sorting the entire array. Shouldn’t you pass the
minandmaxindexes toInsertionSort?Another option is to simply do no work on small partitions during
OptQSort2. Then perform a singleInsertionSortpass over the entire array afterOptQSort2has done its work.