`
yidongkaifa
  • 浏览: 4062627 次
文章分类
社区版块
存档分类
最新评论

冒泡排序

 
阅读更多

冒泡排序是一种比较简单直观的排序方法。代码如下:

void bubble_sort(int array_data[], int array_length)
{
for(int i = 0; i < array_length; i++)
for(int j = array_length - 1; j>i; j--)
{
if(array_data[j] < array_data[j-1])
{
int data = array_data[j];
array_data[j] = array_data[j-1];
array_data[j-1] = data;
}
}

}

测试数据:

int testArrayData[] = {5, 2, 4, 6, 1, 3, 10, 9, 8, 12, 7, 15, 100, 234, 45, 67, 322, 444, 123, 3567,1256,1234567,2176};

测试结果:

1 5 2 4 6 3 7 10 9 8 12 15 45 100 234 67 123 322 444 1256 3567 2176 1234567
1 2 5 3 4 6 7 8 10 9 12 15 45 67 100 234 123 322 444 1256 2176 3567 1234567
1 2 3 5 4 6 7 8 9 10 12 15 45 67 100 123 234 322 444 1256 2176 3567 1234567
1 2 3 4 5 6 7 8 9 10 12 15 45 67 100 123 234 322 444 1256 2176 3567 1234567
1 2 3 4 5 6 7 8 9 10 12 15 45 67 100 123 234 322 444 1256 2176 3567 1234567
1 2 3 4 5 6 7 8 9 10 12 15 45 67 100 123 234 322 444 1256 2176 3567 1234567
1 2 3 4 5 6 7 8 9 10 12 15 45 67 100 123 234 322 444 1256 2176 3567 1234567
1 2 3 4 5 6 7 8 9 10 12 15 45 67 100 123 234 322 444 1256 2176 3567 1234567
1 2 3 4 5 6 7 8 9 10 12 15 45 67 100 123 234 322 444 1256 2176 3567 1234567
1 2 3 4 5 6 7 8 9 10 12 15 45 67 100 123 234 322 444 1256 2176 3567 1234567
1 2 3 4 5 6 7 8 9 10 12 15 45 67 100 123 234 322 444 1256 2176 3567 1234567
1 2 3 4 5 6 7 8 9 10 12 15 45 67 100 123 234 322 444 1256 2176 3567 1234567
1 2 3 4 5 6 7 8 9 10 12 15 45 67 100 123 234 322 444 1256 2176 3567 1234567
1 2 3 4 5 6 7 8 9 10 12 15 45 67 100 123 234 322 444 1256 2176 3567 1234567
1 2 3 4 5 6 7 8 9 10 12 15 45 67 100 123 234 322 444 1256 2176 3567 1234567
1 2 3 4 5 6 7 8 9 10 12 15 45 67 100 123 234 322 444 1256 2176 3567 1234567
1 2 3 4 5 6 7 8 9 10 12 15 45 67 100 123 234 322 444 1256 2176 3567 1234567
1 2 3 4 5 6 7 8 9 10 12 15 45 67 100 123 234 322 444 1256 2176 3567 1234567
1 2 3 4 5 6 7 8 9 10 12 15 45 67 100 123 234 322 444 1256 2176 3567 1234567
1 2 3 4 5 6 7 8 9 10 12 15 45 67 100 123 234 322 444 1256 2176 3567 1234567
1 2 3 4 5 6 7 8 9 10 12 15 45 67 100 123 234 322 444 1256 2176 3567 1234567
1 2 3 4 5 6 7 8 9 10 12 15 45 67 100 123 234 322 444 1256 2176 3567 1234567
1 2 3 4 5 6 7 8 9 10 12 15 45 67 100 123 234 322 444 1256 2176 3567 1234567
1 2 3 4 5 6 7 8 9 10 12 15 45 67 100 123 234 322 444 1256 2176 3567 1234567

上面的排序结果是正确的。但是,仔细观察,发现在循环4次后,冒泡排序已经完成,因此

后面的20次循环可以优化掉。

优化后的代码:增加了一个boolean变量,如果在一次循环中,没有发生[j-1]与[j]的数据交换,

则认为排序已经结束。

void bubble_sort(int array_data[], int array_length)
{
bool finished = false;
for(int i = 0; i < array_length; i++)
{
finished = true;
for(int j = array_length - 1; j>i; j--)
{
if(array_data[j] < array_data[j-1])
{
int data = array_data[j];
array_data[j] = array_data[j-1];
array_data[j-1] = data;
finished = false;
}
}

if(finished == true)
{
break;
}
}
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics