forked from walkthetalk/study_solution
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinsertion_sort.cpp
52 lines (48 loc) · 1.05 KB
/
insertion_sort.cpp
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
#include <vector>
#include <iostream>
/// @CLRS \name INSERTION -SORT(A)
void non_inc_insertion_sort(std::vector<int> & A)
{
/// @CLRS for j = 2 to A.length
for (std::size_t j = 1; j < A.size(); ++j) {
/// @CLRS key = A[j]
auto key = A[j];
/// @CLRS // Insert A[j] into the sorted sequence A[1 .. j-1].
/// @CLRS i = j - 1
auto i = j;
/// @CLRS while i > 0 and A[i] > key
while (i > 0 && A[i-1] > key) {
/// @CLRS A[i + 1] = A[i]
A[i] = A[i-1];
/// @CLRS i = i - 1
--i;
}
/// @CLRS A[i + 1] = key
A[i] = key;
}
}
void non_dec_insertion_sort(std::vector<int> & A)
{
for (std::size_t j = 1; j < A.size(); ++j) {
auto key = A[j];
// Insert A[j] into the sorted sequence A[0 .. j-1].
auto i = j;
while (i > 0 && A[i-1] < key) {
A[i] = A[i-1];
--i;
}
A[i] = key;
}
}
int main(void)
{
std::vector<int> A = {5,2,4,6,1,3};
//std::vector<int> A = {31, 41, 59, 26, 41, 58};
non_inc_insertion_sort(A);
//non_dec_insertion_sort(A);
for (auto & i : A) {
std::cout << i << " ";
}
std::cout << std::endl;
return 0;
}