在python中使用二进制搜索进行插入排序

时间:2018-01-12 14:57:22

标签: python

我需要对下面的代码提供一些帮助,我的任务是更改插入排序以使用给定的二进制搜索功能。

def binarySearch(aList, start, end, value): 
#Return the position where value is or should be inserted.

    while start <= end: 
        mid = (start + end) // 2 
        if aList[mid] == value: 
            return mid 
        if value < aList[mid]: 
            end = mid - 1 
        else: 
            start = mid + 1 
    return start

def insertionSort(aList):
#Sort aList in ascending order. 

    for index in range(1, len(aList)):
        key = aList[index]
        pos = index
        while pos > 0 and aList[pos - 1] > key:
            aList[pos] = aList[pos - 1]
            pos = pos - 1
        aList[pos] = key

我用来测试函数的代码是:

numbers = [71, 32, 22, 19, 18, 1, 15, 40]
insertionSort(numbers)
print(numbers)

任何帮助都表示赞赏,因为我心不在焉

1 个答案:

答案 0 :(得分:0)

def binary_search(arr, val, start, end):
    if start == end:    #折半到最后start和end可能会相等,递归退出条件之一
        if arr[start] > val:
            return start
        else:
            return start+1

    if start + 1 == end:    #折半到最后start和end相差1,递归退出条件之一
        return start+1

    mid = (start+end)//2
    if arr[mid] < val:
        return binary_search(arr,val,mid, end)
    elif arr[mid] > val:
        return binary_search(arr, val, start, mid)
    else:
        return mid   #折半遇到mid值与val相等,递归退出条件之一


def insertion_sort(arr:list):
    for i in range(1, len(arr)):
        if arr[i] <= arr[0]:
            index = 0
        elif arr[i] >= arr[i-1]:
            continue
        else:
            index = binary_search(arr[0:i],arr[i],0, i-1)
        arr = arr[:index]+ [arr[i]] + arr[index:i] + arr[i+1:]
    return arr

arr = [30,20,80,40,50,10,60,70,90]
insertion_sort(arr)