欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

用函数实现二分查找

程序员文章站 2022-03-13 18:21:29
...

问题及代码:

#include <stdio.h>
int binary_search(int arr[], int n, int k);
#define SIZE 10
int main( )
{
    int d[SIZE] = {1,3,9,12,32,41,45,62,75,77};
    int key,index;
    printf("Input a key you want to search: ");
    scanf("%d", &key);
    index = binary_search(d, SIZE, key);
    if(index >= 0)
        printf("The index is %d .\n", index);
    else
        printf("Not found.\n");
    return 0;
}

int binary_search(int arr[],int n,int k)
{
    int i=-1;
    int low=0,high=n-1,mid;
    while(low<=high)
    {
        mid=(low+high)/2;
        if(arr[mid]==k)
        {
            i=mid;
            break;
        }
        else if(arr[mid]>k)
        {
            high=mid-1;
        }
        else
        {
            low=mid+1;
        }
    }
    return i;
}