zoukankan      html  css  js  c++  java
  • 算法——二分搜索

    思路:首先从数组中间的数把数组分成两部分,如果查找的数比中间的数大,说明接下来需要查找右边的部分,令中间的的下标+1为下一次开始查找的开始位置,再从low到high之间查找,一直循环。

    [root@bogon code]# cat erfen.c 
    #include<stdio.h>
    int work(int x,int a[],int len)
    {
        int low,mid,high;
        low=0;
        high=len-1;
        while(low<=high)   //注意需要=号
        {
            mid=(low+high)/2;   //mid中间的下标
            if(x>a[mid])    //查找的值比中间下标mid位置上的值大
                low=mid+1;   //从mid的下一个位置开始查找,把范围缩小
            else if(x<a[mid])
                high=mid-1;
            else
                return mid; 
        }
        return -1;   //找不到
    }
    int main()
    {
        int a[10]={1,2,3,4,5,6,7,8,9,10};
        int n;
        printf("please input a search num
    ");
        scanf("%d",&n);
        int t=work(n,a,10);
        if(t==-1)
            printf("no this num
    ");
        else
            printf("this num in %d
    ",t);
        return 0;
    }
    [root@bogon code]# gcc erfen.c 
    [root@bogon code]# ./a.out
    please input a search num
    7
    this num in 6
    [root@bogon code]# 
    
  • 相关阅读:
    vue-router路由器的使用
    组件间数据传递
    引用模块和动态组件
    vue自定义全局和局部指令
    vue实例的属性和方法
    vue生命周期以及vue的计算属性
    vue 发送ajax请求
    安装vue-cli脚手架
    vue指令详解
    scrapy-redis组件的使用
  • 原文地址:https://www.cnblogs.com/biaopei/p/7730602.html
Copyright © 2011-2022 走看看