Chinaunix首页 | 论坛 | 博客
  • 博客访问: 135204
  • 博文数量: 42
  • 博客积分: 2521
  • 博客等级: 少校
  • 技术积分: 440
  • 用 户 组: 普通用户
  • 注册时间: 2009-07-31 21:29
文章分类

全部博文(42)

文章存档

2011年(1)

2010年(33)

2009年(8)

我的朋友

分类:

2010-08-25 20:11:52

 

最近看算法和数据结构,感觉下面这本书,很经典,易读。

《数据结构(C语言版)》
作者:()Ellis Horowitz ()Sartaj Sahni ()Susan Anderson-Freed 
译者:李建中 张岩 李治军
出版社:机械工业出版社

以下为书中,几个常见的查找和排序算法的C的实现,感觉很不错。

#define SWAP(x,y,t) ((t) = (x), (x) = (y), (y) = (t))
#define COMPARE(x,y) ((x) < (y) ? -1 : ((x) == (y)) ? 0 : 1)

*************************************************
                查            找
*************************************************
/*search an array, list, that has n numbers. Return i, if
list[i] = searchnum. Return -1, if searchnum is not in the list*/


#define MAX_SIZE 1000
typedef struct{
    int key;
    /* other fields */
} element;
element list[MAX_SIZE];

1.顺序查找
int seqsearch(int list[], int searchnum, int n)
{
    int i;
    for(i = 0; i < n; i++)
        if(list[i] == searchnum) break;
        return ((i < n) ? i : -1);
}

2.折半查找
int binsearch(element list[], int searchnum, int n)
{
    int left = 0, right = n-1, middle;
    while(left <= right){
        middle = (left + right) / 2;
        switch(COMPARE(list[middle].key, searchnum)){
            case -1 : left = middle + 1; break;
            case 0 : return middle;
            case 1 : right = middle - 1;
        }
    }
    returen -1;
}

管理员在2009年8月13日编辑了该文章文章。 -->

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