排序算法——冒泡排序

冒泡排序的写法很多,关键就是两侧循环的写法和里面的比较if (a[j] > a[j+1]):
最容易记得写法,肯定没有错误,但是不太好理解是什么意思
for (int i=0; i<count-1; i++)
{
for (int j=0; j<count-1; j++)
{
///
}
}

下边的写法比较好理解一点,外层每次循环都会把当前最大值进行沉底

count-1次沉底之后,所有最大值都沉底了,顺序就排好了


// tt.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"

void sort(int a[], int count)
{
	int tempValue;
	for (int i=count-1; i>=1; i--)
	{
		for (int j=0; j<=i-1; j++)
		{
			if (a[j] > a[j+1])
			{
				tempValue = a[j];
				a[j] = a[j+1];
				a[j+1] = tempValue;
			}
		}
	}
}

int _tmain(int argc, _TCHAR* argv[])
{
	int a[10] = {5,7,4,9,0,8,1,2,6,3};
	sort(a, 10);

	return 0;
}

但是上面的做法,终归不符合冒泡这个意思,看看下边的这个写法,每次都会把最小的排到上边:

void pop_sort(int array[], int len)
{
	for (int i=len-1;i>0;i--)
	{
		for (int j=len-2;j>=len-1-i;j--)
		{
			if (array[j]>array[j+1])
			{
				int temp = array[j];
				array[j]=array[j+1];
				array[j+1]=temp;
			}
		}
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值