冒泡排序、优化

#include <iostream>
using namespace std;

void print(int * a,int n)
{
	for(int i = 0; i < n; i++)
	{
		cout << a[i] << ' ';
	}
	cout << endl;
}

void sort(int * a,int n)
{
	for(int i = 0; i < n; i++)
	{
		bool flag = true;
		for(int j = 0; j < n-i-1;j++)
		{
		//注释掉的这几行应该放在外一层,不过放在这一层也很有趣,相当于啥也没做
		//	bool flag = true;
			if(a[j] > a[j+1])
			{
				int temp;
				temp = a[j];
				a[j] = a[j+1];
				a[j+1] = temp;
				flag = false;
			}
		//	if(flag)
		//	{
		//		break;
		//	}
		}
		if(flag)
		{
			break;
		}
		cout << "第" << i << "次:";
		print(a,n);
	}
}

int main()
{
	int a[10] = {1,4,7,8,5,2,3,6,9,0};
	sort(a,10);
	cout << "排序结果:" << endl; ;
	print(a,10);
}
/*  程序运行结果
第0次:1 4 7 5 2 3 6 8 0 9 
第1次:1 4 5 2 3 6 7 0 8 9 
第2次:1 4 2 3 5 6 0 7 8 9 
第3次:1 2 3 4 5 0 6 7 8 9 
第4次:1 2 3 4 0 5 6 7 8 9 
第5次:1 2 3 0 4 5 6 7 8 9 
第6次:1 2 0 3 4 5 6 7 8 9 
第7次:1 0 2 3 4 5 6 7 8 9 
第8次:0 1 2 3 4 5 6 7 8 9 
排序结果:
0 1 2 3 4 5 6 7 8 9 
*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值