Friday, August 5, 2016

Optimized quick sort

In the previous article we discussed about quick sort algorithm. In this article we are going to discuss about further optimizing quick sort.

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


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 

You can find the complete implementation of QuickIn Sort algorithm with tests on github here.

No comments:

Post a Comment

Optimized quick sort

In the previous article  we discussed about quick sort algorithm. In this article we are going to discuss about further optimizing quick sor...