用二分查找法在一维有序数组中查找某个值并输出其下标值

关键字与左右标的大小比较

#include
int main()
{
    int  arr[] = { 0, 1, 2, 3, 4, 6, 7, 9 };
    int left = 0;
    int right = sizeof(arr) / sizeof(arr[0])-1;
    int mid = 0;
    int key = 4;
    while (left <= right)
    {
        mid=(left + right) / 2;
        if (arr[mid]>key)
        {
            right = mid - 1;
        }
        else if (arr[mid] < key)
        {
            left = mid + 1;
        }
        else
            break;
    }
    if (left <= right)
    {
        printf("找到了下标是%d\n", arr[mid]);
    }
    else
    {
        printf("找不到");
    }
    return 0;
}

用二分查找法在一维有序数组中查找某个值并输出其下标值_第1张图片

你可能感兴趣的:(C,二分查找,一维数组)