这篇文章主要为大家详细介绍了C++实现选择排序,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
本文实例为大家分来源gao*daima.com搞@代#码网享了C++实现选择排序的具体代码,供大家参考,具体内容如下
一、思路
每次取剩下没排序的数中的最小数,然后,填到对应位置。(可以使用a[0]位置作为暂存单元)
如下:
二、实现程序
#include using namespace std; const int maxSize = 100; template void SelectSort(T arr[], int n); // 选择排序 int main(int argc, const char * argv[]) { int i, n, arr[maxSize]; cout <> n; cout << "请输入要排序的数:"; for(i = 1; i > 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 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]
测试数据:
7
20 12 50 70 2 8 40
测试结果:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持gaodaima搞代码网。
以上就是C++实现选择排序(selectionSort)的详细内容,更多请关注gaodaima搞代码网其它相关文章!