介绍
这篇文章主要讲解了c++如何实现选择排序,内容清晰明了,对此有兴趣的小伙伴可以学习一下,相信大家阅读完之后会有帮助。
<强>一、思路强>
每次取剩下没排序的数中的最小的数,然后,填到对应位置。(可以使用一个[0]位置作为暂存单元)
如下:
<强>二,实现程序强>
# include & lt; iostream> 使用名称空间性病; const int最大尺寸=100; template<类T> 空白SelectSort (T arr [], int n);//选择排序 int主要(int命令行参数个数,const char * argv []) { int i n, arr(最大尺寸); cout & lt; & lt;“请输入要排序的数的个数:“; ,cin祝辞的在n; cout & lt; & lt;“请输入要排序的数:“; (i=1;我& lt;=n;我+ +)//arr[0]不存放值,用来做暂存单元 ,cin祝辞的在加勒比海盗[我]; cout & lt; & lt;“排序前:“;& lt; & lt;endl; (i=1;我& lt;=n;我+ +) cout & lt; & lt;加勒比海盗[我]& lt; & lt;“;“; cout & lt; & lt;endl; SelectSort (arr n); cout & lt; & lt;“排序后:“;& lt; & lt;endl; (i=1;我& lt;=n;我+ +) cout & lt; & lt;加勒比海盗[我]& lt; & lt;“;“; cout & lt; & lt;endl; 返回0; }//直接选择排序 模板& lt;类T> 空白SelectSort (T arr [], int n) { int i, j, pos机; (i=1;我& lt;n;我+ +){//共作n - 1趟选择排序 pos=我;//保存最小数的位置 (j=我;j & lt;=n;j + +){//找比arr[我]更小的值 如果(arr [j] & lt;加勒比海盗(pos)) { pos=j;//指向更小的数的位置 } } 如果(pos !=i){//找到了更小的值,就交换位置 arr [0]=arr[我];//arr[0]作为暂存单元 arr[我]=arr (pos); arr (pos)=arr [0]; } }//}//SelectSort
测试数据:7
20 12 50 70 2 8 40
测试结果:
看完上述内容,是不是对c++如何实现选择排序有进一步的了解,如果还想学习更多内容,欢迎关注行业资讯频道。