冒泡排序(高级版)之C++实现

一、源代码:BubbleSortHigh.cpp

 #include<iostream>
using namespace std; /*定义输出一维数组的函数*/
void print(int array[], int n)
{
for (int i = ; i < n; i++)
{
cout << array[i] << " ";
}
cout << endl;
} /*定义冒泡排序的函数,升序排序,返回交换次数*/
int bubbleSort(int array[], int n)
{
//定义变量,记录交换次数
int count = ;
//定义中间变量temp
int temp;
//遍历数组(进行排序)
cout << "开始对数组进行排序了..." << endl;
for (int i = ; i < n; i++)
{
//定义变量是否进行交换了,默认为未交换,置为0
bool swap = false;
for (int j = ; j < n - - i; j++)
{
cout << "第" << (i + ) << "趟第" << (j + ) << "次排序" << endl;
//如果左边的数大于右边的数就进行交换顺序
if (array[j] > array[j + ])
{
temp = array[j];
array[j] = array[j + ];
array[j + ] = temp;
cout << array[j] << "和" << array[j + ] << "互换了" << endl;
//输出此时数组的顺序
cout << "数组此时的顺序是:";
print(array, );
//每交换一次,记录数加1
count++;
//如果交换了,将swap置为1
swap = true;
}
}
//如果未交换,即swap=0,则进行下一趟
if (!swap)
{
break;
}
}
cout << "数组排序结束了..." << endl;
return count;
} int main()
{
//定义待排序的一维数组
int array[] = { , , , , , , , , , };
//输出原始数组
cout << "原始数组是:" << endl;
print(array, );
//对数组进行排序
int count = bubbleSort(array, );
//输出排序后的数组
cout << "排序后的数组是:" << endl;
print(array, );
cout << "共交换" << count << "次" << endl;
}

二、运行效果(与初级版运行效果比较,过程更简单)

最新文章

  1. 深入理解js的变量提升和函数提升
  2. 【iOS】UITabView/UICollectionView 全选问题
  3. Bootstrap 3 简介
  4. 建站集成软件包 XAMPP搭建后台系统与微信小程序开发
  5. 一种透明效果的view
  6. spring+hibernate+struts整合(2)
  7. 配置ModSecurity防火墙与OWASP规则
  8. CentOS6.3挂载读写NTFS分区
  9. CSS3 :nth-of-type() 选择器
  10. Dom对象和JQuery对象的详细介绍及其区别
  11. Codeforces Round #416 (Div. 2)(A,思维题,暴力,B,思维题,暴力)
  12. 网页验证码出不来,读取验证码时出错:javax.imageio.IIOException: Can&#39;t create cache file!
  13. current account(经常账户)
  14. Python re 模块
  15. Confluence 6 针对 key &quot;cp_&quot; 或 &quot;cps_&quot; 的 &quot;Duplicate Entry&quot; 问题解决
  16. 被监测teamviewer被检测出用于商业用途
  17. C/C++ 分支预测(likely unlikely)
  18. 中控考勤机SDK使用中员工姓名的处理( c# )
  19. React Native控件之Picker
  20. pl/sql编程2-综合

热门文章

  1. vtk 基础概念
  2. vi的复制粘贴命令 -- (转)
  3. Servlet笔记4--ServletConfig接口和ServletContext接口
  4. Servlet笔记1--概述
  5. 渗透测试===使用BURPSUIT暴力破解某网站的手机验证码
  6. aarch64_g1
  7. 使用postman做接口测试(二)
  8. WPF Devexpress GridControl Value与Display转换
  9. MongoDB的安装与使用
  10. Hash 分布均衡算法