1. 程式人生 > >資料結構與演算法 二分法查詢【Python與C】的實現

資料結構與演算法 二分法查詢【Python與C】的實現

程式碼如下:

Python:

def ErFen(List ,Number ,Len):
    left = 0
    high = Len - 1

    while left <= high:
        mid = (left + high)//2
        if Number > List[mid]:
            left = mid + 1
        elif Number < List[mid]:
            high = mid - 1
        elif Number == List[mid]:
            return mid
    return -1
a = [1,2,3,4,5,6,7,8,9,10]
number = int(input('請輸入想要查詢的數字:'))
Len = len(a)

print(ErFen(a,number,Len))

C:

#include <stdio.h>  
  
/*binsearch : find x in v[0] <= v[1] <= ... <= v[n-1] */  
int binsearch(int x, int v[], int n){  
    int low, high, mid;  
  
    low = 0;  
    high = n - 1;  
  
    while ( low <= high ) {  
        mid = (low + high) / 2;  
        if(x < v[mid]){  
            high = mid - 1;  
        }  
        else if(x > v[mid]){  
            low = mid + 1;  
        }  
        else{ /*found match*/  
            return mid;  
        }  
    }  
  
    return -1;  
}  
  
int main(){  
    int array[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};  
    int location;  
    int number = 9;  
    location = binsearch(number, array, 11);  
    printf("%d\n", location);  
    return 0;  
}