服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C/C++ - C++实现选择排序(selectionSort)

C++实现选择排序(selectionSort)

2021-09-01 14:11ChanJose C/C++

这篇文章主要为大家详细介绍了C++实现选择排序,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了C++实现选择排序的具体代码,供大家参考,具体内容如下

一、思路

每次取剩下没排序的数中的最小数,然后,填到对应位置。(可以使用a[0]位置作为暂存单元)

如下:

C++实现选择排序(selectionSort)

二、实现程序

?
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
#include <iostream>
using namespace std;
 
const int maxSize = 100;
 
template<class T>
void SelectSort(T arr[], int n); // 选择排序
 
int main(int argc, const char * argv[]) {
 int i, n, arr[maxSize];
 
 cout << "请输入要排序的数的个数:";
 cin >> n;
 cout << "请输入要排序的数:";
 for(i = 1; i <= n; i++) // arr[0]不存放值,用来做暂存单元
 cin >> arr[i];
 cout << "排序前:" << endl;
 for(i = 1; i <= n; i++)
 cout << arr[i] << " ";
 cout << endl;
 SelectSort(arr, n);
 cout << "排序后:" << endl;
 for(i = 1; i <= n; i++)
 cout << arr[i] << " ";
 cout << endl;
 return 0;
}
 
// 直接选择排序
template <class T>
void SelectSort(T arr[], int n) {
 int i, j, pos;
 
 for(i = 1; i < n; i++) { // 共作n-1趟选择排序
 pos = i; // 保存最小数的位置
 for(j = i; j <= n; j++) { // 找比arr[i]更小的值
  if(arr[j] < arr[pos]) {
  pos = j; // 指向更小的数的位置
  }
 }
 if(pos != i) { // 找到了更小的值,就交换位置
  arr[0] = arr[i]; // arr[0]作为暂存单元
  arr[i] = arr[pos];
  arr[pos] = arr[0];
 }
 } // for
} // SelectSort

测试数据:

7

20 12 50 70 2 8 40

测试结果:

C++实现选择排序(selectionSort)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/chuanzhouxiao/article/details/89006784

延伸 · 阅读

精彩推荐