• (经典) K&R的名著<<C程序设计语言>>二分查找


    #include<stdio.h>
    
    //查找成功则返回所在下标否则返回-1
    int binsearch(int A[], int n,int a)
    {
       int low, high, mid;
       low = 0;
       high = n -1;
       while ( low <= high) {    /// 这里必须是 <=
            mid = (low+high) / 2;
            if (A[mid] == a)
               return mid;
            else if(A[mid]<a)
               low = mid +1;
            else
               high=mid-1;
        }
       return -1;
    }
    
    
    int main()
    {   int a[]={1,2,44,44,99};
        printf("%d",binsearch(a,5,44));
    }
    //二分查找,递归算法
    #include <iostream>
    #include<stdio.h>
    
    using namespace std;
    
    int binSearch(int a[],int low,int high,int b)
    {
        int mid = (high-low)/2;
        if(a[mid] == b) return mid;
    
        if(a[mid] > b)  binSearch(a,low,mid-1,b);
    
        if(a[mid] < b)  binSearch(a,mid+1,high,b);
    }
    
    
    int main()
    {   int a[] = {2,6,8,88888,88888888}; int yy;
        yy = binSearch(a,0,4,8);
        printf("%d",yy);
        return 0;
    }
  • 相关阅读:
    python_控制台输出带颜色的文字方法
    模拟数据库作业
    js笔记
    CSS 笔记
    html 笔记
    必备技能-Git 使用规范流程
    python 闭包
    30个python编程技巧!
    python 面向对象
    python 线程
  • 原文地址:https://www.cnblogs.com/cs-lcy/p/7076896.html
Copyright © 2020-2023  润新知