二分查找数组中的某个特定数字

下面展示python代码

def binary_search(my_list, item):
    low = 0
    high = len(my_list) - 1
    while low <= high:
        mid = (low + high) // 2
        guess = my_list[mid]
        if guess == item:
            return mid
        elif guess > item:
            high = mid - 1
        else:
            low = mid + 1
    return None
my_list = [1, 3, 5, 7, 9]
print(binary_search(my_list, 3))
print(binary_search(my_list, -1))

cpp代码

#include <iostream>
using namespace std;

int binary_search(int list[], int item, int size)
{
    int low = 0;
    int high = size - 1;

    while (low <= high)
    {
        int mid = (low + high) / 2;
        int guess = list[mid];
        if (guess == item)
        {
            return mid;
        }
        else if (guess > item)
        {
            high = mid - 1;
        }
        else if (guess < item)
        {
            low = mid + 1;
        }
    }
    return -1; // 返回 -1 表示未找到
}

int main()
{
    int my_list[] = {1, 3, 5, 7, 9};
    int size = sizeof(my_list) / sizeof(my_list[0]); // 计算数组大小
    int m, n;
    m = binary_search(my_list, 3, size);
    n = binary_search(my_list, -1, size);
    cout << m << endl;
    cout << n << endl;
}

cpp代码,不能直接在函数中使用sizeof,需要利用指针。所以我们先行跳过。

posted @ 2023-11-06 17:09  YE-  阅读(6)  评论(0编辑  收藏  举报