# coding:utf8 __author__ = 'bluesli' def binary_search(data_source,find_n): mid = int(len(data_source)/2)#这里直接通过长度获取中间值,无需再添加变量low,height,middle这些变量; if len(data_source)>=1: #利用切片后的长度作为结束标志 if data_source[mid] > find_n: print('data in left') print(data_source[:mid]) binary_search(data_source[:mid],find_n) elif data_source[mid]<find_n: print('data is in right') print(data_source[mid:]) binary_search(data_source[mid:],find_n) #利用切片可以很快的获取值所在的范围的序列;然后直接获取长度,利用长度再次找到中间位置; else: print('find it',data_source[mid]) print(mid) else: print('cannot find') if __name__ == '__main__': data = list(range(1, 10, 3)) print(data) binary_search(data,7)
c 语言实现二分查找:相比于python空间复杂读高了;
int BinySerch(int *arr, int x, int lengh)//设计参数,由于是整形数组,所以我们必须传递他 { //长度否则数组传参时会发生降级 int left = 0, right = lengh - 1; int mid ; while (left <= right) { mid = left + (right - left) / 2; if (x < arr[mid]) { right = mid - 1; } else if (x > arr[mid]) { left = mid + 1; } else { return mid; } } return -1; } int main()//测试用例 { int x = 0; int arr[11] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int lengh = sizeof(arr) / sizeof(arr[0]); for (int i = 0; i < 12; i++) { printf("%d ",BinySerch(arr, i, lengh)); } system("pause"); return 0; }