简体   繁体   中英

Insertion sort using binary search in python

I need a little help with the code below, I have been tasked with changing the insertion sort to use the given binary search function.

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

The code I am using to test the function is:

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

Any help is appreciated as I am having a mind blank

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM