算法导论-二分查找

# Author:Liusw
# 查找问题
import math
#  nums 是升序
def searchNum(nums,target):
    # 先将数组nums进行排序
    # nums = insertionSort(nums,"asc")
    # print()
    result = False
    middle = math.floor((len(nums) - 1) / 2)
    if nums[middle] == target :
        result = True
    elif nums[middle] > target:
        nums = nums[0:middle]
    else:
        nums = nums[middle+1:len(nums)-1]
    if not result :
        if len(nums) <= 2 :
            for num in nums:
                if num == target:
                    result = True
            return result
        else:
            result = searchNum(nums,target)

    return result

if __name__ == '__main__':
    # nums = insertionSort([3,4,5,1,2,56,34,23,75,32,90])
    print(searchNum([1,2,3,4,5,6,7,8,9,15,35,67,89],16))

 

你可能感兴趣的:(算法导论)