-
Notifications
You must be signed in to change notification settings - Fork 0
/
insertion_sort.hpp
55 lines (48 loc) · 1.15 KB
/
insertion_sort.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#pragma once
#include <cstddef> // std::size_t
#include <array>
#include <vector>
namespace wndx {
namespace srt {
#ifndef SRT_SWAP_P_Q
#define SRT_SWAP_P_Q
/**
* swap pointers
*/
inline void swap(auto* p, auto* q)
{
auto tp { *p }; // tmp ptr
*p = *q;
*q = tp;
}
#endif // SRT_SWAP_P_Q
/**
* Sort the given array using insertion sort.
* Concept: if array is sorted from [0, i] => insert at i+1.
*/
template<typename T>
inline void insertion_sort(T *a, const std::size_t n)
{
for (std::size_t i = 1; i < n; i++) {
for (std::size_t j = i; j > 0 && a[j] < a[j - 1]; j--)
srt::swap(&a[j - 1], &a[j]);
}
}
template<typename T, std::size_t n>
inline void insertion_sort(std::array<T, n> &a)
{
for (std::size_t i = 1; i < n; i++) {
for (std::size_t j = i; j > 0 && a[j] < a[j - 1]; j--)
srt::swap(&a[j - 1], &a[j]);
}
}
template<typename T>
inline void insertion_sort(std::vector<T> &a)
{
for (std::size_t i = 1; i < a.size(); i++) {
for (std::size_t j = i; j > 0 && a[j] < a[j - 1]; j--)
srt::swap(&a[j - 1], &a[j]);
}
}
} // namespace srt
} // namespace wndx