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

用函数写二分查找

程序员文章站 2024-03-17 15:09:22
...
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
int binary_search(int arr[],int n,int sz)
{
    int left = 0;
    int right = sz-1;
    int mid = 0;

    while(left<=right)
    {
        mid = (left+right)/2;
        if(arr[mid]>n)
        {
            right = mid-1;
        }
        else if(arr[mid] < n)
        {
            left = mid+1;
        }
        else
            return mid;
    }
    return -1;
}
int main()
{
    int arr[]={1,2,3,4,5,6,7,8,9,10};

    int n = 0;
    int ret = 0;
    int sz=sizeof(arr)/sizeof(arr[0]);
    printf("请输入要查找的:");
    scanf("%d",&n);
    ret = binary_search(arr,n,sz);
    if(ret==-1)
        printf("找不到\n");
    else
        printf("找到了,下标是:%d\n",ret);
    return 0;
}
相关标签: 函数 二分查找