用c语言编写二分查找法

   二分法的适用范围为有序数列,这方面很有局限性。

#include<stdio.h>

//二分查找法
void binary_search(int a[],int start,int mid,int end);

int main()
{
    int iLength,istars,i,iTimes,iNumber,n;
    int a[100];
    printf("please enter the length of the array:
 ");
    scanf("%d",&iLength);
    printf("please enter the number:
");
    for(i=0;i<iLength;i++)
    {
        scanf("%d",&a[i]);
    }


    printf("please enter the number that you want:
");
    scanf("%d",&istars);
    /*if(n==istars)
    {
        
    }
    else
    {
        printf("sorry ,without this number
");
    }*/
     binary_search(a,0,istars,iLength);
    
}
void  binary_search(int a[],int start,int iPut,int end)

{
    int i,j,k,n;
    i=start;
    j=end;
    k=(i+j)/2;
    n=0;
    while(i<j)
    //while(i<=k && j>=k) 这个写的本身就有漏洞,就是对整个程序的不理解
    {
        n++;
        if(iPut>a[k])
        {
            i=k+1;
        }
        if(iPut<a[k])
        {
            j=k-1;
        }
        if(iPut==a[k])
        {
            printf("the number need %d times to find......a[%d]=%d
",n,k,iPut);
        
            break;
        }
        
    }

if(n==0)
        printf("failed
");
    
}

 这是开始参考书目,自己编写的程序,但是程序本身能准确运行范围内的数字,一旦输入范围外的数字则出现卡壳现象。因此,要在源代码中改进。



#include<stdio.h>

//二分查找法
void binary_search(int a[],int start,int iPut,int end);

int main()
{
    int iLength,istars,i,iTimes,iNumber,n;
    int a[100];
    printf("please enter the length of the array:
 ");
    scanf("%d",&iLength);
    printf("please enter the number:
");
    for(i=0;i<iLength;i++)
    {
        scanf("%d",&a[i]);
    }


    printf("please enter the number that you want:
");
    scanf("%d",&istars);
    /*if(n==istars)
    {
        
    }
    else
    {
        printf("sorry ,without this number
");
    }*/
     binary_search(a,0,istars,iLength);
    
}
void binary_search(int a[],int start,int iPut,int end)

{
    int i,j,k,n,m;
    m=0;
    i=start;
    j=end;

    n=0;
    while(i<j)
    //while(i<=k && j>=k) 这个写的本身就有漏洞,就是对整个程序的不理解
    {
        n++;
        k=(i+j)/2;//这个为关键!!!!!
        if(iPut>a[k])
        {
            i=k+1;
        }
        if(iPut<a[k])
        {
            j=k-1;
        }
        if(iPut==a[k])
        {
            printf("the number need %d times to find......a[%d]=%d
",n,k,iPut);
            m++;
            break;
        }
        
    }
    if(m==0)
        printf("failed
");
    
}



第一次代码错误的主要原因为中间值k的位置放错了。k要放在循环之中,要不然无法形成循环,中间值就永远都是中间值,无法利用其的逼近功能,

与此同时编写代码多了,时常会把 if 和while用混,这就需要具体问题,if只执行一次,while则是一个循环,使用while的时候要写上跳出条件,要不然会无休止的运行下去,导致死循环。

原文地址:https://www.cnblogs.com/xiaochige/p/5946296.html