c语言实现数组的二分查找

二分查找是一种效率比较高的查找顺序表中的元素的方法,其时间复杂度为O(log2n)。

具体代码如下所示:

#include <stdio.h>
#include <stdlib.h>
int cmp(int *a,int *b){//define a function used for the function qsort.
    return (*a)-(*b);
}
int main(){
    int a[100];
    printf("Please input the length of the array :");
    int n; //define the array length
    scanf("%d",&n);
    printf("Please input the number that in your array.\n");
    for(int i=0;i<n;i++){//Initialization the array.
        scanf("%d",&a[i]);
    }

    qsort(a,n,sizeof(int),cmp);//sort the array and let it in ascending order.
    for(int i=0;i<n;i++){
        printf("%d ",a[i]);
    }
    printf("\nPlease input the number that you want to find :");
    int number;//define the number that you want to find.
    scanf("%d",&number);
    int low=0,high=n-1,middle,location;
    //low:pointed to the lowest subscript of the array.
    //high:pointed to the largest subscript of the array.
    //middle:pointed to the middle subscript of the array.
    //location:represent the real location of the number that you want find.
    if(number>a[high]||number<a[low]){//In this way ,the number is overflow from the array.
        printf("The number is overflow from the array.\n");
    }else{
        int flag=0;
        while((!flag)&&low<=high){//If we not find the number and "low" is lower than "high",do this loop.
             middle=(low+high)/2;
            if(number==a[middle]){//OK,we find the target number.
                location=middle;//noted the subscript
                flag=1;
                break;//break the loop
            }else if(number<a[middle]){//update the high value
                high=middle-1;
            }else if(number>a[middle]){//update the low value
                low=middle+1;
            }
        }
        if(flag){//We find the target number ,print the result
            printf("We can find the number %d ,it's location is %d.\n",number,location);
        }else{//We don't find the target number,print the number.
            printf("We can not find the number %d,it doesn't in the array.\n",number);
        }
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值