Sorting algorithms/Insertion sort: Difference between revisions

m
(Updated D entry)
Line 240:
 
=={{header|C++}}==
Uses C++11. Compile with
Uses binary search via std::upper_bound() to find the insertion position in logarithmic time, then performs the insertion via std::rotate(), in linear time.
g++ -std=c++11 insertion.cpp
 
Uses binary search via std::upper_bound() to find the insertion position in logarithmic time, and then performs the insertion via std::rotate(), in linear time.
<lang cpp>#include <algorithm>
#include <iostream>
#include <iterator>
 
template<typename IterRandomAccessIterator>
void insertion_sort(RandomAccessIterator begin, RandomAccessIterator end) {
for (Iterauto i = begbegin; i != end; ++i) {
std::rotate(std::upper_bound(begbegin, i, *i), i, i + 1);
}
}
 
int main() {
template<typename Iter>
int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};
void insertion_sort(Iter begstd::begin(a), Iter std::end(a));
{
copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, " "));
for (Iter i = beg; i != end; ++i)
std::cout << "\n";
std::rotate(std::upper_bound(beg, i, *i), i, i+1);
}</lang>
Output:
<pre>
-199 -52 2 3 33 56 99 100 177 200
</pre>
 
=={{header|C sharp|C#}}==