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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

ChanJose   2021-04-22 我要评论

一、思路

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

如下:

二、实现程序

#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

测试结果:

猜您喜欢

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们