用Python实现二分查找代码演示
用Python实现二分查找,本范例要求给定的数组是已经排好序的
""" 皮蛋编程(https://www.pidancode.com) 创建日期:2022/3/28 功能描述:用Python实现二分查找代码演示 """ def search(a, m): low = 0 high = len(a) - 1 while (low <= high): mid = int((low + high) / 2) midval = a[mid] if midval < m: low = mid + 1 elif midval > m: high = mid - 1 else: print(mid) return mid print(-1) return -1 if __name__ == "__main__": a = [1, 3, 5, 8, 34, 45, 67, 89, 233] m = 34 search(a, m)
输出结果:4
以上代码在python3.9环境测试通过。
相关文章