码迷,mamicode.com
首页 > 编程语言 > 详细

线性查找与二分查找(python)

时间:2019-07-10 23:14:23      阅读:232      评论:0      收藏:0      [点我收藏+]

标签:二分查找   lambda   dex   code   lam   line   sort   color   enum   

# -*- coding: utf-8 -*-

number_list = [0, 1, 2, 3, 4, 5, 6, 7]


def linear_search(value, iterable):
    for index, val in enumerate(iterable):
        if val == value:
            return index
    return -1


assert linear_search(5, number_list) == 5


def linear_search_v2(predicate, iterable):
    for index, val in enumerate(iterable):
        if predicate(val):
            return index
    return -1


assert linear_search_v2(lambda x: x == 5, number_list) == 5


def linear_search_recusive(array, value):
    if len(array) == 0:
        return -1
    index = len(array)-1
    if array[index] == value:
        return index
    return linear_search_recusive(array[0:index], value)


assert linear_search_recusive(number_list, 5) == 5
assert linear_search_recusive(number_list, 8) == -1
assert linear_search_recusive(number_list, 7) == 7
assert linear_search_recusive(number_list, 0) == 0


def binary_search_recursive(sorted_array, beg, end, val):
    if beg >= end:
        return -1
    mid = int((beg + end) / 2)  # beg + (end-beg)/2
    if sorted_array[mid] == val:
        return mid
    elif sorted_array[mid] > val:
        return binary_search_recursive(sorted_array, beg, mid, val)    
    else:
        return binary_search_recursive(sorted_array, mid+1, end, val)


def test_binary_search_recursive():
    a = list(range(10))
    for i in a:
        assert binary_search_recursive(a, 0, len(a), i) == i

    assert binary_search_recursive(a, 0, len(a), -1) == -1
    assert binary_search_recursive(a, 0, len(a), 10) == -1

 

线性查找与二分查找(python)

标签:二分查找   lambda   dex   code   lam   line   sort   color   enum   

原文地址:https://www.cnblogs.com/muzinan110/p/11166981.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!