Leyanshi
Articles13
Tags6
Categories2

Categories

一言

Archive

C++ 笔记 2026-06-04

C++ 笔记 2026-06-04

排序 pt.2

插入排序

伪代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
include bits/stdc++.h
using namespace std;
int list n;
int list list;
void swap(int* a, int* b) {//懒得写了,反正会写}
main:
int n;
input n; input list[n];// for repeat
遍历 int i=0; i<n; i++ // n次,0~n-1
插入list[i]到n[i]
if i==0 continue;//跳出了本次循环
int lol = n[i]
遍历 int j = i; j>=0; j--
如果 n[j]大于lol,替换这两个

真代码:

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
#include <bits/stdc++.h>
using namespace std;

int main() {
int n;
cin >> n;
int list[n];
for (int i = 0; i < n; i++) {
cin >> list[i];
}
for (int i = 0; i < n; i++) {
if (i == 0) continue;
int lol = list[i];
int index = i;
for (int j = i; j >= 0; j--) {
if (list[j] > lol) {
swap(list[j], list[index]);
index--;
}
}
}
for (int i = 0; i < n; i++) {
cout << list[i] << " ";
}
return 0;
}

桶排序

如果数字范围为1~100
伪代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
伪代码(不遵循语法,只练逻辑)
头文件bits/stdc++.h,使用std域
vector<vector<int>> buckets(101);
int list[1e5+1];
int result[1e5+1]; // 外层内存肯定够,才2万
main:
定义int n并输入; 根据n输入n个list的值;
遍历 int i=0; i < n; i++
buckets[list[i]].push_back(list[i]);
定义int position = 0;
遍历 和上面一样
遍历 int j = 0;,和上面差不多
result[position]=buckets[i][j],并且position++
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
#include <bits/stdc++.h>
using namespace std;

vector<vector<int>> buckets(101);
int list_[100001]; // 避免与函数名冲突
int result[100001];

int main() {
int n;
cin >> n;

for (int i = 0; i < n; i++) {
cin >> list_[i];
buckets[list_[i]].push_back(list_[i]);
}

int position = 0;
for (int i = 0; i < 101; i++) {
for (int j = 0; j < buckets[i].size(); j++) {
result[position] = buckets[i][j];
position++;
}
}

return 0;
}