Chinaunix首页 | 论坛 | 博客
  • 博客访问: 24987
  • 博文数量: 11
  • 博客积分: 1410
  • 博客等级: 上尉
  • 技术积分: 105
  • 用 户 组: 普通用户
  • 注册时间: 2007-04-28 14:08
文章分类

全部博文(11)

文章存档

2010年(7)

2009年(4)

我的朋友
最近访客

分类: C/C++

2009-03-23 14:22:23

双向冒泡排序,插入排序例程,适合少量数据排序。

#include <stdio.h>
#include <string.h>

// 调试输出宏定义
#ifdef DEBUG
 #define debug(...)            \
    do {                       \ 
        printf(__VA_ARGS__);   \
    } while (0)
#else
 #define debug(...)
#endif

 

// 双向冒泡排序
void bubble_sort(unsigned int a[], unsigned int n)
{
    unsigned int top = 0;
    unsigned int bottom = n - 1;
    unsigned int mark = top;
    unsigned int tmp;
    unsigned int i;

    do {

        // 下沉
        for (i = top; i < bottom; i++) {
            if (a[i] > a[i+1]) {
                tmp = a[i];
                a[i] = a[i+1];
                a[i+1] = tmp;
                mark = i;
                debug("v%d\n", mark);
            }
        }
        bottom = mark;

        // 上浮
        debug("%2d -- %2d\n", top, bottom);
        for (i = bottom; i > top; i--) {
            if (a[i-1] > a[i]) {
                tmp = a[i];
                a[i] = a[i-1];
                a[i-1] = tmp;
                mark = i;
                debug("^%d\n", mark);
            }
        }
        top = mark;
        debug("%2d -- %2d\n", top, bottom);
    } while (top < bottom);
}

// 直接插入排序
void insert_sort(unsigned int a[], unsigned int n)
{
    unsigned int i, j;
    unsigned int tmp;

    for (i = 1; i < n; i++) {
        tmp = a[i];
        j = i;
        while (j > 0 && a[j-1] > tmp) {
             a[j] = a[j-1];
             j--;
        }
        a[j] = tmp;
    }
}

阅读(586) | 评论(0) | 转发(0) |
0

上一篇:没有了

下一篇:位运算

给主人留下些什么吧!~~