The optimized version of quick sort algorithm we are going to use is known as QuickIn Sort. QuickIn Sort is significantly faster in practice than other O (n log n) algorithms.
Previous article explains how quick sort works. As described in it, quick sort do the real sorting in it's partitioning step. Every time when the recursive function is called, the size of the partition gets smaller.
Even for a very large data set, the recursive function call occur till the partition size is the smallest possible. When this partitioning occur, there is a threshold size of partition after which, the partitioning costs more than other O (N^2) algorithms. This is an inefficiency of quick sort algorithm.
where A, B, k and c are constants , N is the number of elements in the data set.
The L.H.S of the inequality gives the time complexity of quick sort while R.H.S gives the time complexity of other sorting algorithms.
Insertion sort is an algorithm which has an average time complexity of O (N^2). But the time efficiency of insertion sort depends on how sorted the data set is.
For small N values above inequality becomes true.
eg:
The quickIn sort algorithm use insertion sort for partitions of size less than the threshold value. The threshold value needs to be determined by testing.
Following is an implementation of quickInSort function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void quickInSort(int arr[SIZE], int left, int right) | |
{ | |
if (left >= right) | |
return; | |
if ((right - left) < TRESHOLD) // do insertionSort if less than treshold | |
{ | |
insertionSort(arr, left, right); | |
return; | |
} | |
int piv_pos = partition(arr, left, right); // get pivot position after partitioning | |
quickInSort(arr, left, piv_pos); //Sort left part | |
quickInSort(arr, piv_pos + 1, right); //Sort right part | |
} |
The partition function will be the same as in normal quick sort algorithm. Please refer previous article for the partition function.
Following is an implementation of insertion sort function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void insertionSort(int arr[SIZE], int left, int right) | |
{ | |
int i, key, j; | |
for (i = left + 1; i <= right; i++) | |
{ | |
key = arr[i]; | |
j = i - 1; | |
while (j >= 0 && arr[j] > key) | |
{ | |
arr[j + 1] = arr[j]; | |
j = j - 1; | |
} | |
arr[j + 1] = key; | |
} | |
} |
You can find the complete implementation of QuickIn Sort algorithm with tests on github here.