Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1680141
  • 博文数量: 1493
  • 博客积分: 38
  • 博客等级: 民兵
  • 技术积分: 5834
  • 用 户 组: 普通用户
  • 注册时间: 2009-08-19 17:28
文章分类

全部博文(1493)

文章存档

2016年(11)

2015年(38)

2014年(137)

2013年(253)

2012年(1054)

2011年(1)

分类:

2012-05-11 08:32:12

原文地址:排序——冒泡排序 作者:EnjoyKernel

冒泡排序:
①需要“冒泡”的形式来排序,大气泡向后去|小气泡向前来。
②冒泡,比较(交换)相邻的元素。
③总共冒N次泡
④已有序的数目等于冒泡的数

一个标识:(注意一下)
冒泡排序的内循环for的j的条件测试是外循环i相关的。

下标越界的避免:
需要比较相邻的元素,因此j与j+1注意越界的避免。

源码:
  1. void swap(int *a, int *b)
  2. {
  3.     int *temp;
  4.     *temp = *a;
  5.     *a = *b;
  6.     *b = *temp;
  7. }

  8. // note: compare the two number who are adjacent.
  9. void bubble_sort(int a[], int n)
  10. {
  11.     for(int i = 0; i < n; i++)
  12.     {
  13.         // compare a[j]&a[j+1], so j must be less than n-1.
  14.         // n-1-i means some numbers at the end of the array are sorted.
  15.         for(int j = 0; j < (n-1)-i; j++)
  16.         {
  17.             // the bigger number is bubbled to right side.
  18.             if(a[j] > a[j+1])
  19.             {
  20.                 swap(a[j], a[j+1]);
  21.             }
  22.         }

  23.         output(a, n);
  24.     }
  25. }

阅读(324) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~