MyraMath
insertion_sort.h
Go to the documentation of this file.
1 
2 // ========================================================================= //
3 // This file is part of MyraMath, copyright (c) 2014-2019 by Ryan A Chilton //
4 // and distributed by MyraCore, LLC. See LICENSE.txt for license terms. //
5 // ========================================================================= //
6 
7 #ifndef MYRAMATH_UTILITY_INSERTION_SORT_H
8 #define MYRAMATH_UTILITY_INSERTION_SORT_H
9 
15 #include <cstddef> // size_t
16 
17 namespace myra {
18 
20 template<class T> void insertion_sort(T* begin, T* end)
21  {
22  int I = static_cast<int>(end-begin);
23  for (int i = 1; i < I; ++i)
24  {
25  T x = begin[i];
26  int j = i-1;
27  while (j >= 0 && x < begin[j])
28  { begin[j+1] = begin[j]; --j; }
29  begin[j+1] = x;
30  }
31  }
32 
34 template<class T> void insertion_sort(T* begin, size_t N)
35  { insertion_sort(begin,begin+N); }
36 
38 template<class T, class Comparator> void insertion_sort(T* begin, T* end, const Comparator& cmp)
39  {
40  int I = static_cast<int>(end-begin);
41  for (int i = 1; i < I; ++i)
42  {
43  T x = begin[i];
44  int j = i-1;
45  while (j >= 0 && cmp(x,begin[j]) )
46  { begin[j+1] = begin[j]; --j; }
47  begin[j+1] = x;
48  }
49  }
50 
52 template<class T, class Comparator> void insertion_sort(T* begin, size_t N, const Comparator& cmp)
53  { insertion_sort(begin,begin+N,cmp); }
54 
55 } // namespace
56 
57 #endif
Definition: syntax.dox:1
void insertion_sort(T *begin, T *end)
Sorts the T&#39;s within the range [begin,end). Note T must be assignable.
Definition: insertion_sort.h:20