冒泡排序(高级版)之C++实现
2024-10-06 13:34:04
冒泡排序(高级版)之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;
}
二、运行效果(与初级版运行效果比较,过程更简单)
最新文章
- 深入理解js的变量提升和函数提升
- 【iOS】UITabView/UICollectionView 全选问题
- Bootstrap 3 简介
- 建站集成软件包 XAMPP搭建后台系统与微信小程序开发
- 一种透明效果的view
- spring+hibernate+struts整合(2)
- 配置ModSecurity防火墙与OWASP规则
- CentOS6.3挂载读写NTFS分区
- CSS3 :nth-of-type() 选择器
- Dom对象和JQuery对象的详细介绍及其区别
- Codeforces Round #416 (Div. 2)(A,思维题,暴力,B,思维题,暴力)
- 网页验证码出不来,读取验证码时出错:javax.imageio.IIOException: Can&#39;t create cache file!
- current account(经常账户)
- Python re 模块
- Confluence 6 针对 key ";cp_"; 或 ";cps_"; 的 ";Duplicate Entry"; 问题解决
- 被监测teamviewer被检测出用于商业用途
- C/C++ 分支预测(likely unlikely)
- 中控考勤机SDK使用中员工姓名的处理( c# )
- React Native控件之Picker
- pl/sql编程2-综合