二分查找python和C++实现

python版

class BinarySearch():

    def search_binary(self, list, item):
        low = 0
        high = len(list) - 1

        while (low <= high):
            mid = (low + high) // 2  # “/”是浮点数除法,但是在此程序中需要整除,所以要用“%”或者“//”
            guess = list[mid]
            if guess == item:
                return mid
            elif guess > item:
                high = mid - 1
            else:
                low = mid + 1
        return None

    def search_recursive(self, list, item, low, high):
        if high >= low:
            mid = (high + low) // 2
            guess = list[mid]

            if guess == item:
                return mid
            elif guess > item:
                return self.search_recursive(list, item, low, mid - 1)
            else:
                return self.search_recursive(list, item, mid + 1, high)
        else:
            return None

if __name__ == "__main__":
    bs = BinarySearch()
    my_list = [1, 3, 5, 7, 9, 10, 22]
    print(bs.search_binary(my_list, 22))
    print(bs.search_recursive(my_list, 5, 0, 6))

C++版

#include "iostream"
using namespace std;

void binarySearch(int data_array[], int element, int len)
{
    int low = 0;
    int high = len;
    while (low <= high)
    {
        int mid = (low + high)/2; 
        int guess = data_array[mid];

        if (guess == element)
        {
            cout<<"Element found at "<<mid<<" th index"<<endl ;
            return ;
        }
        else if (guess > element)
        {
            high = mid - 1;
        }
        else
        {
            low = mid + 1;
        }
    }
    cout<<"Element Not Found"<<endl ;
    return ; //number not found
}
int main()
{
    int data_array[] = {2,10,23,44,100,121};
    int length = sizeof(data_array) / sizeof(int);

    binarySearch(data_array, 3, length) ;  // not found case
    binarySearch(data_array, 2, length) ; // found at corner case
    binarySearch(data_array, 44, length) ; //found at middle case
    return 0;
}



版权声明:本文为qq_42598221原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。