数组的二分查找

二分查找是一种效率比较高的查找顺序表中的元素的方法,其时间复杂度为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;
}

猜你喜欢

转载自blog.csdn.net/qq_39769995/article/details/82957184