Skip to content

Commit 94068c7

Browse files
author
Jason
committed
feat: Selection Sort 选择排序
1 parent 502b191 commit 94068c7

File tree

5 files changed

+46
-4
lines changed

5 files changed

+46
-4
lines changed

.gitignore

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
1-
*.out
1+
*.out
2+
.vscode

README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
- other
77

88
## Run
9-
### [BubbleSort.cpp](./sorting/BubbleSort.cpp)文件为例运行步骤如下:
9+
### [QuickSort.cpp](./sorting/QuickSort.cpp)文件为例运行步骤如下:
1010
1. 进入对应目录 `cd sorting`
11-
2. 编译cpp文件 `g++ BubbleSort.cpp ./lib/DoubleVector.cp` ,默认会输出 `a.out` 文件 (具体命令视情况而定)
11+
2. 编译cpp文件 `g++ QuickSort.cpp ./lib/DoubleVector.cpp` ,默认会输出 `a.out` 文件 (具体命令视情况而定)
1212
3. 执行编译后的文件 `./a.out`

sorting/QuickSort.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ using namespace std;
1010
* 整个排序过程只需要三步:
1111
*  (1)在数据集之中,选择一个元素作为"基准"(pivot)。
1212
*  (2)所有小于"基准"的元素,都移到"基准"的左边;所有大于"基准"的元素,都移到"基准"的右边。
13-
*  (3)对"基准"左边和右边的两个子集,不断重复第一步和第二步,直到所有子
13+
*  (3)对"基准"左边和右边的两个子集,不断重复第一步和第二步,直到所有子集只剩下一个元素为止
1414
* 参考链接: https://www.ruanyifeng.com/blog/2011/04/quicksort_in_javascript.html
1515
*/
1616

sorting/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,4 +5,5 @@
55
- [Quick Sort 快速排序](./QuickSort.cpp)
66
- 参考链接
77
- [快速排序(Quicksort)的Javascript实现](https://www.ruanyifeng.com/blog/2011/04/quicksort_in_javascript.html)
8+
- [Selection Sort 选择排序](./SelectionSort.cpp)
89
- other

sorting/SelectionSort.cpp

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
#include <iostream>
2+
#include <vector>
3+
#include <algorithm>
4+
#include "./lib/DoubleVector.h"
5+
using namespace std;
6+
7+
/**
8+
* 选择排序
9+
*/
10+
11+
int main()
12+
{
13+
vector<double> list = cinDoubleVector();
14+
15+
vector<double> selectionSort(vector<double>);
16+
selectionSort(list);
17+
18+
coutDoubleVector(list);
19+
20+
return 0;
21+
}
22+
23+
vector<double> selectionSort(vector<double> list)
24+
{
25+
int len = list.size();
26+
if (len <= 1)
27+
return list;
28+
for (int i = 0; i < len - 1; i++)
29+
{
30+
int minIdx = i;
31+
for (int j = 0; j < len; j++)
32+
{
33+
if (list[j] < list[minIdx])
34+
minIdx = j;
35+
}
36+
swap(list[i], list[minIdx]);
37+
}
38+
39+
return list;
40+
}

0 commit comments

Comments
 (0)