Euphoria
insertionsort.h
Go to the documentation of this file.
1 #pragma once
2 
3 
4 #include <cstddef>
5 
6 namespace eu::core
7 {
8  template <typename T, typename TSortFunc>
9  void
10  do_inplace_insertion_sort(std::vector<T>* pointer_to_array, TSortFunc sort_func)
11  {
12  auto& array = *pointer_to_array;
13  const auto length = array.size();
14 
15  size_t index = 1;
16  while(index < length)
17  {
18  size_t j = index;
19  while(j > 0 && sort_func(array[j - 1], array[j]) > 0)
20  {
21  std::swap(array[j], array[j - 1]);
22  j = j - 1;
23  }
24  index = index + 1;
25  }
26  }
27 
28  template <typename T, typename TSortFunc>
29  std::vector<T>
30  get_insertion_sorted(const std::vector<T>& array, TSortFunc sort_func)
31  {
32  auto copy = array;
33  do_inplace_insertion_sort(&copy, sort_func);
34  return copy;
35  }
36 
37  template <typename T>
38  int
39  default_compare_for_insertion_sort(const T& lhs, const T& rhs)
40  {
41  if(lhs == rhs)
42  {
43  return 0;
44  }
45  return lhs < rhs ? -1 : 1;
46  }
47 
48  template <typename T>
49  std::vector<T>
50  get_insertion_sorted(const std::vector<T>& array)
51  {
52  return get_insertion_sorted(array, default_compare_for_insertion_sort<T>);
53  }
54 
55 }
56 
void copy(char *dst, const std::string &src, const std::string::size_type &count)
Copy a string to a character buffer, adding null terminator at the end.
Definition: stringutils.cc:293
int default_compare_for_insertion_sort(const T &lhs, const T &rhs)
Definition: insertionsort.h:39
std::vector< T > get_insertion_sorted(const std::vector< T > &array, TSortFunc sort_func)
Definition: insertionsort.h:30
void do_inplace_insertion_sort(std::vector< T > *pointer_to_array, TSortFunc sort_func)
Definition: insertionsort.h:10
constexpr StringMerger array
Definition: stringmerger.h:91