STL Sort Analysis

xuwenzhi@cityuniversity.edu

What's Sort?

Common used sort algorithms

Quick Sort 

Merge Sort

Heap Sort 

Insertion Sort

Counting Sort

Bubble Sort

Selection Sort

Care about what?

  • Time and Space complexity

  • Stable or Unstable

  • In-place or not In-place

  • Frequently Swap or not

How C++ implement Sort?

std::sort(a.begin(), a.end());

 

Introspective Sort

- A hybrid sort method.

Quick Sort + Heap Sort + Insertion Sort

Quick Sort vs. Heap Sort

 

  • Generally faster
  • Unstable Worst Time : O(n^2)
  • In-place sorting

 

 

  • Generally slower
  • Stable (nlogn)
  • In-place sorting

Heap Sort

Quick Sort

5

5

10

0

3

1

Pivot

i

j

Insertion Sort

Behind Principles

  1. At first std::sort() use Quick Sort. Time complexity is O(nlogn).
  2. When the current range is less than threshold, it will use insertion sort.
  3.  In the first step, if the recursion level is too deep, it will change to use heap sort.

Source Code

template<typename _RandomAccessIterator>
	inline void
	sort(_RandomAccessIterator __first, _RandomAccessIterator __last)
	{
     //...
     if (__first != __last)
     {
       std::__introsort_loop(__first, __last,
                 std::__lg(__last - __first) * 2);
       std::__final_insertion_sort(__first, __last);
     }
}
template<typename _RandomAccessIterator, typename _Size>
      void
      __introsort_loop(_RandomAccessIterator __first,
               _RandomAccessIterator __last,
               _Size __depth_limit)
      {
        while (__last - __first > int(_S_threshold))
      {
        if (__depth_limit == 0)
          {
            _GLIBCXX_STD_A::partial_sort(__first, __last, __last);
            return;
          }
        --__depth_limit;
        _RandomAccessIterator __cut =
          std::__unguarded_partition_pivot(__first, __last);
        std::__introsort_loop(__cut, __last, __depth_limit);
        __last = __cut;
      }
      }

Reference

https://www.geeksforgeeks.org/sorting-algorithms/

https://gcc.gnu.org/onlinedocs/gcc-4.7.2/libstdc++/api/a01462_source.html

http://www.student.montefiore.ulg.ac.be/~merciadri/docs/papers/heap-quick-comparison.pdf

Thanks!

Stlsort

By xuwenzhi

Stlsort

  • 91