Given an integer array, sort it using introsort sorting algorithm.

Introsort Overview

Introsort is an efficient in-place sorting algorithm, which usually beats all other sorting algorithms in terms of performance. Due to its high performance, it is used in several standard library sort functions, including some C++ sort implementations.

Introsort is a comparison sort, meaning that it can sort items of any type for which a less-than relation is defined. It is usually not a stable sort, which means that if two elements have the same value, they might not hold the same relative position in the output as they did in the input.

Introsort Implementation

Introsort is a hybrid of Quicksort and heapsort algorithm. A hybrid algorithm combines two or more other algorithms that solve the same problem such that the resulting algorithm is better than the individual algorithms. Introsort begins with Quicksort and switches to heapsort when the recursion depth exceeds a level based on (the logarithm of) the total number of elements being sorted. When the total number of elements is below some threshold, introsort can switch to a non-recursive sorting algorithm such as insertion sort that performs fewer swaps, comparisons or other operations on such small arrays.

Practice this algorithm

Following is the C++ implementation of the introsort algorithm is similar to the GNU Standard C++ library. It uses introsort with a maximum depth of 2.log2(n), followed by an insertion sort on partitions smaller than 16. The Quicksort algorithm is optimized by better pivot selection.

Download  Run Code

Output:

-15 -12 -8 -7 -4 0 1 2 3 4 5 6 7 9 10 12

Introsort Performance

Introsort sorting algorithm provides both fast average performance and (asymptotically) optimal worst-case performance. Both the average-case and worst-case time complexity of introsort are O(n.log(n)), where n is the size of the input.

The auxiliary space required by the introsort algorithm is O(n) for the call stack when the naive Quicksort algorithm is used. To keep the stack depth bounded by O(log(n)), recur first into the partition’s smaller side, then use a tail call to recur into the other.

 
References: https://en.wikipedia.org/wiki/Introsort