选择排序之C++实现

一、源代码:SelectSort.cpp

 /*
选择排序(从小到大)的基本思想是,首先,选出最小的数,放在第一个位置;
然后,选出第二小的数,放在第二个位置;
以此类推,直到所有的数从小到大排序。
在实现上,我们通常是先确定第i小的数所在的位置,然后,将其与第i个数进行交换。
*/
#include<iostream>
using namespace std;
/*定义输出一维数组的函数*/
void print(int array[], int n)
{
for (int i = ; i < n; i++)
{
cout << array[i] << " ";
}
cout << endl;
} int selectSort(int array[], int n)
{
//定义变量,记录交换次数
int count = ;
//假设最小值所在的位置,默认为0,即第一个元素
int min_index = ;
//定义中间变量,存储临时数据
int temp;
//遍历数组(进行排序)
cout << "开始对数组进行排序了..." << endl;
for (int i = ; i < n - ; i++)
{
//假设当前的元素是第i小的元素,保存当前位置
min_index = i;
for (int j = i + ; j < n; j++)
{
cout << "第" << (i + ) << "趟第" << (j + ) << "次排序" << endl;
//判断当前的元素是否小于假设的第i小元素
if (array[min_index]>array[j])
{
//重新设置第i小的元素位置
min_index = j;
}
}
//判断当前位置的元素是否等于假设的第i小元素,如果不等于则交换这两个元素
if (min_index != i)
{
temp = array[min_index];
array[min_index] = array[i];
array[i] = temp;
cout << array[min_index] << "和" << array[i] << "互换了" << endl;
//输出此时数组的顺序
cout << "数组此时的顺序是:";
print(array, );
//每交换一次,记录数加1
count++;
}
}
cout << "数组排序结束了..." << endl;
return count;
} int main()
{
//定义待排序的一维数组
int array[] = { , , , , , , , , , };
//输出原始数组
cout << "原始数组是:" << endl;
print(array, );
//对数组进行排序
int count = selectSort(array, );
//输出排序后的数组
cout << "排序后的数组是:" << endl;
print(array, );
cout << "共交换" << count << "次" << endl;
return ;
}

二、运行效果

最新文章

  1. Bestcoder#5 1002
  2. PHP中global与$GLOBALS[&#39;&#39;]的区别
  3. div赋值,取值和input赋值,取值
  4. 启动tomcat,报java.lang.NoClassDefFoundError
  5. PHPCMS V9静态化HTML生成设置及URL规则优化
  6. ThreadContext
  7. (medium)LeetCode 221.Maximal Square
  8. ZooKeeper(3.4.5) - 原生 API 的简单示例
  9. Poj3484-Showstopper(二分脑洞题)
  10. jQuery-ui datepicker的使用演示代码
  11. Win10下CISCO VPN Client无法安装解决方案
  12. python 全栈开发,Day2(正式)
  13. 微信分享config:ok 但自定义内容无效
  14. 三层结构与MVC
  15. 新建gradle文件
  16. Android 布局类控件
  17. C#的托管和非托管的简单理解
  18. 上课总结-数据库Chapter2: 关系数据库
  19. JAVA 利用反射自定义数据层框架
  20. android开发之自定义圆形ImagView

热门文章

  1. perl6 HTTP::UserAgent发送post
  2. C#基础学习之FileStream
  3. Python之容器类Collections
  4. docker stack 部署 mysql 5.6
  5. npm 下载node-zookeeper包
  6. Python_oldboy_自动化运维之路(四)
  7. CNN细节
  8. Spring 事务管理基础知识点
  9. 消息 8101,级别 16,状态 1,第 1 行仅当使用了列列表并且 IDENTITY_INSERT 为 ON 时,才能为表&#39;CUSTOMER_TBL&#39;中的标识列指定显式值。
  10. js中的Object.seal()与Object.freeze()