Skip to content

Commit a7a6e38

Browse files
committed
更新选择排序
1 parent 9c123ec commit a7a6e38

File tree

4 files changed

+22
-7
lines changed

4 files changed

+22
-7
lines changed

Algorithm/BubbleSort.h

-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
// 冒泡排序
2-
32
void BubbleSort(vector<int>& v) {
43
int temp;
54
for (int i = 0; i < v.size() - 1; ++i) {

Algorithm/BubbleSort_orderly.h

+3-5
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,12 @@
1-
// 冒泡排序(跳过有序的改进版)
2-
1+
// 冒泡排序(改进版)
32
void BubbleSort_orderly(vector<int>& v) {
43
int temp;
54
bool orderly = false;
65
for (int i = 0; i < v.size() - 1 && !orderly; ++i) {
76
orderly = true;
87
for (int j = 0; j < v.size() - 1 - i; ++j) {
9-
if (v[j] > v[j + 1])
10-
{
11-
orderly = false;
8+
if (v[j] > v[j + 1]) { // 从小到大
9+
orderly = false; // 发生交换则仍非有序
1210
temp = v[j];
1311
v[j] = v[j + 1];
1412
v[j + 1] = temp;

Algorithm/SelectionSort.h

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
// 选择排序
2+
void SelectionSort(vector<int>& v) {
3+
int min, temp;
4+
for (int i = 0; i < v.size() - 1; ++i) {
5+
min = i;
6+
for (int j = i + 1; j < v.size(); ++j) {
7+
if (v[j] < v[min]) { // 标记最小的
8+
min = j;
9+
}
10+
}
11+
if (i != min) { // 交换到前面
12+
temp = v[i];
13+
v[i] = v[min];
14+
v[min] = temp;
15+
}
16+
}
17+
}

README.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,8 @@
4343
### 排序
4444

4545
* [冒泡排序](Algorithm/BubbleSort.h)
46-
* [冒泡排序(跳过有序的改进版)](Algorithm/BubbleSort_orderly.h)
46+
* [冒泡排序(改进版)](Algorithm/BubbleSort_orderly.h)
47+
* [选择排序](Algorithm/BubbleSort_orderly.h)
4748

4849
## Problems
4950

0 commit comments

Comments
 (0)