philsupertramp/game-math
Loading...
Searching...
No Matches
sorting.h
Go to the documentation of this file.
1#pragma once
2
3#include "Matrix.h"
4#include <type_traits>
5#include <vector>
6
7
15template<typename T, typename = typename std::enable_if<std::is_arithmetic<T>::value, T>::type>
16void insertion_sort(const T& elem, std::vector<T>& vec, const int& current_index) {
17 int i = current_index;
18 for(; i > 1; i--) {
19 if(vec[i - 1] < elem) { break; }
20 vec[i] = vec[i - 1];
21 }
22 vec[i] = elem;
23}
32template<typename T, typename = typename std::enable_if<std::is_arithmetic<T>::value, T>::type>
33std::vector<T> sort(const std::vector<T>& in) {
34 std::vector<T> out(in.size());
35 int n = -1;
36 for(auto elem : in) {
37 // Insertion sort
38 n = n + 1;
39 insertion_sort(elem, out, n);
40 }
41 return out;
42}
43
44template<typename T>
45void insertion_sort(const T& elem, Matrix<T>& out, const int& current_index) {
46 int i = current_index;
47 if(current_index > 0) {
48 for(; i >= 1; --i) {
49 if(out(i - 1, 0) < elem) { break; }
50 out(i, 0) = out(i - 1, 0);
51 }
52 }
53 out(i, 0) = elem;
54}
55
56template<typename T>
58 bool requires_transposition = in.rows() < in.columns();
59 auto _in = requires_transposition ? in.Transpose() : in;
60 Matrix<T> out = Matrix<T>(std::numeric_limits<T>::min(), _in.rows(), 1);
61 for(int i = 0; i < _in.rows(); ++i) { insertion_sort(_in(i, 0), out, i); }
62 return requires_transposition ? out.Transpose() : out;
63}
64
Definition: Matrix.h:42
constexpr Matrix< T > Transpose() const
Definition: Matrix.h:256
size_t rows() const
Definition: Matrix.h:193
size_t columns() const
Definition: Matrix.h:198
void insertion_sort(const T &elem, std::vector< T > &vec, const int &current_index)
Definition: sorting.h:16
std::vector< T > sort(const std::vector< T > &in)
Definition: sorting.h:33