现在的位置: 首页 > 综合 > 正文

《每日编程》—-《算法》—-《一》—-二分查找

2013年03月08日 ⁄ 综合 ⁄ 共 949字 ⁄ 字号 评论关闭

工作了一段时间了,偶尔看到数据结构,觉得有些陌生,毕竟工作上用的比较少,如果在这样下去可能,大学学的算法和数据结构就会忘光了,必须每天练练手了。

 

给自己的要求也不高,有空的时候就写个小程序,然后放到blog里,注明应该注意的地方,以后看起来也应该比较方便

 

原文地址:http://blog.csdn.net/lengzijian/article/details/8017630

 

/*
    改代码主要来源于《编程之美》3.11
    发现自己写相同代码时,存在相同问题。
    这里记录下容易犯下的错误,
    并且写下可执行代码,方便大家学习。
*/

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

int bisearch(char **arr, int b, int e, char *v)
{
    int midIndex;
    int minIndex = b;
    int maxIndex = e;
    
    printf("v---->%s\n",v);
    
    if(minIndex > maxIndex)
    {
        return -1;
    }
    
    
    while(minIndex < maxIndex - 1)
    {         
        //这里我也用了minIndex + maxIndex 的方式
        //书上说:大数时,会导致和为负数
        midIndex = minIndex + ( maxIndex - minIndex ) / 2;
        if(strcmp(arr[midIndex], v) <= 0)
        {
            minIndex = midIndex;
        }
        else
        {
            maxIndex = midIndex ;
        }

    }
    //想想为什么不在while里直接加判断等于的操作?
    //直接在while循环里面判断:①先判断是否小于②判断是否大于③判断是否等于
    //因为while循环里面的操作会增加。仔细想一想!!
    if(!strcmp(arr[maxIndex], v))
    {
        return maxIndex;
    }
    else if(!strcmp(arr[minIndex], v))
    {
        return minIndex;
    }
    else
    {
        return -2;
    }
}

int main ()
{
    char *arr[10] = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"};
    char *c = "8";
    int a = 0;
    a = bisearch(arr,0,9,c);
    printf("find-->%d\n",a);
}

 

抱歉!评论已关闭.