title: How to implement classic sorting algorithms in modern C++?
body: <p>The <code>std::sort</code> algorithm (and its cousins <code>std::partial_sort</code> and <code>std::nth_element</code>) from the C++ Standard Library is in most implementations <a href="https://stackoverflow.com/q/22339240/819272">a complicated and hybrid amalgamation of more elementary sorting algorithms</a>, such as selection sort, insertion sort, quick sort, merge sort, or heap sort.</p>
  
  <p>There are many questions here and on sister sites such as <a href="https://codereview.stackexchange.com/">https://codereview.stackexchange.com/</a> related to bugs, complexity and other aspects of implementations of these classic sorting algorithms. Most of the offered implementations consist of raw loops, use index manipulation and concrete types, and are generally non-trivial to analyse in terms of correctness and efficiency.</p>
  
  <p><strong>Question</strong>: how can the above mentioned classic sorting algorithms be implemented using modern C++?</p>
  
  <ul>
  <li><strong>no raw loops</strong>, but combining the Standard Library's algorithmic building blocks from <code>&lt;algorithm&gt;</code></li>
  <li><strong>iterator interface</strong> and use of <strong>templates</strong> instead of index manipulation and concrete types</li>
  <li><strong>C++14 style</strong>, including the full Standard Library, as well as syntactic noise reducers such as <code>auto</code>, template aliases, transparent comparators and polymorphic lambdas.</li>
  </ul>
  
  <p><strong>Notes</strong>: </p>
  
  <ul>
  <li>for further references on implementations of sorting algorithms see <a href="http://en.wikipedia.org/wiki/Sorting_algorithm" rel="noreferrer">Wikipedia</a>, <a href="http://rosettacode.org/wiki/Sorting_algorithms" rel="noreferrer">Rosetta Code</a> or <a href="http://www.sorting-algorithms.com/" rel="noreferrer">http://www.sorting-algorithms.com/</a> </li>
  <li>according to <a href="https://github.com/sean-parent/sean-parent.github.com/wiki/presentations/2013-09-11-cpp-seasoning/cpp-seasoning.pdf" rel="noreferrer"><strong>Sean Parent's conventions</strong></a> (slide 39), a raw loop is a <code>for</code>-loop longer than composition of two functions with an operator. So <code>f(g(x));</code> or <code>f(x); g(x);</code> or <code>f(x) + g(x);</code> are not raw loops, and neither are the loops in <code>selection_sort</code> and <code>insertion_sort</code> below.</li>
  <li>I follow Scott Meyers's terminology to denote the current C++1y already as C++14, and to denote C++98 and C++03 both as C++98, so don't flame me for that.</li>
  <li>As suggested in the comments by @Mehrdad, I provide four implementations as a Live Example at the end of the answer: C++14, C++11, C++98 and Boost and C++98. </li>
  <li>The answer itself is presented in terms of C++14 only. Where relevant, I denote the syntactic and library differences where the various language versions differ.</li>
  </ul>