-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsort.h
More file actions
58 lines (51 loc) · 1.42 KB
/
Copy pathsort.h
File metadata and controls
58 lines (51 loc) · 1.42 KB
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
#ifndef CPP_ALGORITHM_SORT_H
#define CPP_ALGORITHM_SORT_H
#include <vector>
namespace Sort
{
/**
* \brief Selection sort algorithm.
* \param seq sequence of elements
* \return sorted sequence
*/
std::vector<int> SelectionSort(std::vector<int>& seq);
/**
* \brief Insertion sort algorithm.
* \param seq sequence of elements
* \return sorted sequence
*/
std::vector<int> InsertionSort(std::vector<int>& seq);
}
// ----------------------------------------------------------------------------
inline std::vector<int> Sort::InsertionSort(std::vector<int>& seq)
{
const int size = static_cast<int>(seq.size());
for (int index = 1; index < size; ++index)
{
int key = index;
while ((key > 0) && (seq[key] < seq[key - 1]))
{
std::swap(seq[key], seq[key - 1]);
key--;
}
}
return seq;
}
// ----------------------------------------------------------------------------
inline std::vector<int> Sort::SelectionSort(std::vector<int>& seq)
{
for (int prev = 0; prev < static_cast<int>(seq.size()); ++prev)
{
int min_index = prev;
for (int next = prev + 1; next < static_cast<int>(seq.size()); ++next)
{
if (seq[min_index] > seq[next])
{
min_index = next;
}
}
std::swap(seq[prev], seq[min_index]);
}
return seq;
}
#endif