Skip to content

Commit 63795fe

Browse files
authored
feat: insertion sort in cpp (doocs#555)
1 parent 85728fc commit 63795fe

File tree

2 files changed

+89
-0
lines changed

2 files changed

+89
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
#include <iostream>
2+
#include <vector>
3+
4+
using namespace std;
5+
6+
void printvec(const vector<int> &vec, const string &strbegin = "", const string &strend = "")
7+
{
8+
cout << strbegin << endl;
9+
for (auto val : vec)
10+
{
11+
cout << val << "\t";
12+
}
13+
14+
cout << endl;
15+
cout << strend << endl;
16+
}
17+
18+
void insertsort(vector<int> &vec)
19+
{
20+
for (int i = 1; i < vec.size(); i++)
21+
{
22+
int j = i - 1;
23+
int num = vec[i];
24+
for (; j >= 0 && vec[j] > num; j--)
25+
{
26+
vec[j + 1] = vec[j];
27+
}
28+
29+
vec[j + 1] = num;
30+
}
31+
32+
return;
33+
}
34+
35+
int main()
36+
{
37+
vector<int> vec = {9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
38+
printvec(vec);
39+
insertsort(vec);
40+
printvec(vec, "after insert sort");
41+
return (0);
42+
}

basic/sorting/InsertionSort/README.md

+47
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,53 @@ func main() {
8585
}
8686
```
8787

88+
### **C++**
89+
90+
```cpp
91+
#include <iostream>
92+
#include <vector>
93+
94+
using namespace std;
95+
96+
void printvec(const vector<int> &vec, const string &strbegin = "", const string &strend = "")
97+
{
98+
cout << strbegin << endl;
99+
for (auto val : vec)
100+
{
101+
cout << val << "\t";
102+
}
103+
104+
cout << endl;
105+
cout << strend << endl;
106+
}
107+
108+
void insertsort(vector<int> &vec)
109+
{
110+
for (int i = 1; i < vec.size(); i++)
111+
{
112+
int j = i - 1;
113+
int num = vec[i];
114+
for (; j >= 0 && vec[j] > num; j--)
115+
{
116+
vec[j + 1] = vec[j];
117+
}
118+
119+
vec[j + 1] = num;
120+
}
121+
122+
return;
123+
}
124+
125+
int main()
126+
{
127+
vector<int> vec = {9, 8, 7, 6, 5, 4, 3, 2, 1, 0};
128+
printvec(vec);
129+
insertsort(vec);
130+
printvec(vec, "after insert sort");
131+
return (0);
132+
}
133+
```
134+
88135
<!-- tabs:end -->
89136
90137
## 算法分析

0 commit comments

Comments
 (0)