Home  >  Q&A  >  body text

请问哪里的问题第一次写python (Binary Search)

#!/usr/bin/python

""" 折半查找算法
"""

#定义函数

def BinarySearch(a, X, N):
    left, right = 0, N-1
    while (left <= right):
        middle = ( left + right ) / 2
        if (X < a[middle]):
            right = middle - 1
        elif (X > a[middle]):
            left = middle + 1
        else:
            return middle
    return -1 #"not found"

#调用函数

arr = [10,20,30,40,50,60,70]
BinarySearch(arr, 40, len(arr))


高洛峰高洛峰2894 days ago845

reply all(2)I'll reply

  • 三叔

    三叔2016-11-16 13:40:05

    #!/usr/bin/python
    # -*- coding: utf-8 -*-
    import random
    # generate an unsorted list
    def generate_unsorted_list(num):
        unsorted_list = []
        for i in range(0, num):
            unsorted_list.append(random.randint(0, 30))
        print unsorted_list
        return unsorted_list
    def binary_search(target, sorted_list):
        list_length = len(sorted_list)
        start, end = 0, list_length-1
        if list_length == 0:
            print 'empty list'
            return -1
        while start < end:
            middle = (start+end)/2
            if target == sorted_list[middle]:
                print 'find index:', middle
                return middle
            elif target < sorted_list[middle]:
                end = middle-1
            else:
                start = middle+1
        print 'not find'
        return -1
    if __name__ == "__main__":
        unsorted_list = generate_unsorted_list(20)
        sorted_list = sorted(unsorted_list)
        print sorted_list
        binary_search(14, sorted_list)


    reply
    0
  • 欧阳克

    欧阳克2016-11-16 13:39:33

    #!/usr/bin/python
    # -*- coding: utf-8 -*-
    import random
    # generate an unsorted list
    def generate_unsorted_list(num):
        unsorted_list = []
        for i in range(0, num):
            unsorted_list.append(random.randint(0, 30))
        print unsorted_list
        return unsorted_list
    def binary_search(target, sorted_list):
        list_length = len(sorted_list)
        start, end = 0, list_length-1
        if list_length == 0:
            print 'empty list'
            return -1
        while start < end:
            middle = (start+end)/2
            if target == sorted_list[middle]:
                print 'find index:', middle
                return middle
            elif target < sorted_list[middle]:
                end = middle-1
            else:
                start = middle+1
        print 'not find'
        return -1
    if __name__ == "__main__":
        unsorted_list = generate_unsorted_list(20)
        sorted_list = sorted(unsorted_list)
        print sorted_list
        binary_search(14, sorted_list)


    reply
    0
  • Cancelreply