用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:\n ");
    scanf("%d",&iLength);
    printf("please enter the number:\n");
    for(i=0;i<iLength;i++)
    {
        scanf("%d",&a[i]);
    }


    printf("please enter the number that you want:\n");
    scanf("%d",&istars);
    /*if(n==istars)
    {
        
    }
    else
    {
        printf("sorry ,without this number\n");
    }*/
     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",n,k,iPut);
        
            break;
        }
        
    }

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

 這是開始參考書目,自己編寫的程序,但是程序本身能准確運行范圍內的數字,一旦輸入范圍外的數字則出現卡殼現象。因此,要在源代碼中改進。



#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:\n ");
    scanf("%d",&iLength);
    printf("please enter the number:\n");
    for(i=0;i<iLength;i++)
    {
        scanf("%d",&a[i]);
    }


    printf("please enter the number that you want:\n");
    scanf("%d",&istars);
    /*if(n==istars)
    {
        
    }
    else
    {
        printf("sorry ,without this number\n");
    }*/
     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",n,k,iPut);
            m++;
            break;
        }
        
    }
    if(m==0)
        printf("failed\n");
    
}
 
         

 

 
        

第一次代碼錯誤的主要原因為中間值k的位置放錯了。k要放在循環之中,要不然無法形成循環,中間值就永遠都是中間值,無法利用其的逼近功能,

與此同時編寫代碼多了,時常會把 if 和while用混,這就需要具體問題,if只執行一次,while則是一個循環,使用while的時候要寫上跳出條件,要不然會無休止的運行下去,導致死循環。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM