冒泡排序的写法很多,关键就是两侧循环的写法和里面的比较if (a[j] > a[j+1]):
最容易记得写法,肯定没有错误,但是不太好理解是什么意思
for (int i=0; i<count-1; i++)
{
for (int j=0; j<count-1; j++)
{
///
}
}
下边的写法比较好理解一点,外层每次循环都会把当前最大值进行沉底
最容易记得写法,肯定没有错误,但是不太好理解是什么意思
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;
}
}
}
}