Python实现二分查找

 

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/3/18 18:48
# @Author  : baoshan
# @Site    : 
# @File    : binarySearch.py
# @Software: PyCharm Community Edition


# 二分查找 数组排序 返回下标
def binarySearch(search_list, target):
    left = 0
    right = len(search_list) - 1
    while left <= right:
        mid = (left + right) >> 1 # 此处采用位运算
        if search_list[mid] == target:
            return mid
        elif search_list[mid] > target:
            right = mid - 1
        else:
            left = mid + 1
    return None


search_list = [1, 3, 4, 6, 8, 9]
print(binarySearch(search_list, 3))

 

输出结果:

 

/Library/Frameworks/Python.framework/Versions/3.5/bin/python3.5 /Users/baoshan/PycharmProjects/myProject/python_weixin_study/binarySearch.py
1

Process finished with exit code 0

 

posted @ 2018-03-18 18:57  宝山方圆  阅读(264)  评论(0编辑  收藏  举报