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

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

给自己的要求也不高,有空的时候就写个小程序,然后放到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);
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值