-
Notifications
You must be signed in to change notification settings - Fork 0
/
selection_sort.hpp
58 lines (51 loc) · 1.34 KB
/
selection_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
56
57
58
#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
template<typename T>
inline void selection_sort(T *a, const std::size_t n)
{
for (std::size_t i = 0; i < n; i++) {
std::size_t x = i; // find the index beyond i with a lower value than i
for (std::size_t j = i + 1; j < n; j++)
if (a[j] < a[x]) x = j;
srt::swap(&a[i], &a[x]);
}
}
template<typename T, std::size_t n>
inline void selection_sort(std::array<T, n> &a)
{
for (std::size_t i = 0; i < n; i++) {
std::size_t x = i; // find the index beyond i with a lower value than i
for (std::size_t j = i + 1; j < n; j++)
if (a[j] < a[x]) x = j;
srt::swap(&a[i], &a[x]);
}
}
template<typename T>
inline void selection_sort(std::vector<T> &a)
{
const std::size_t n = a.size();
for (std::size_t i = 0; i < n; i++) {
std::size_t x = i; // find the index beyond i with a lower value than i
for (std::size_t j = i + 1; j < n; j++)
if (a[j] < a[x]) x = j;
srt::swap(&a[i], &a[x]);
}
}
} // namespace srt
} // namespace wndx