常用算法

快排

def quicksort(lis):
    if len(lis) < 2:
        return lis
    else:
        numb = lis[0]
        left_list = [i for i in lis[1:] if i <= numb]
        right_list = [i for i in lis[1:] if i > numb]
        final_list = quicksort(left_list) + [numb] + quicksort(right_list)
        return final_list

quick_list = quicksort([6,3,5,87,69,52,4,16])
print(quick_list)

  

二分法查找

lis = [3, 4, 5, 6, 16, 52, 69, 87, 95]
def search(lis,item):
    left = 0
    right = len(lis)-1

    while right-left >= 0:
        middle = (right+left) // 2
        if item > lis[middle]:
            left = middle + 1

        elif item < lis[middle]:
            right = middle -1

        else :
            return middle

  

选择排序

def choice_sort(lis):
    min = 0
    min_value = lis[0]

    for i in range(1,len(lis)):
        if min_value >= lis[i]:
            min = i
            min_value = lis[i]
    return min

def app_list(list):
    new_list = []
    for i in range(len(list)):
        new_list.append(list.pop(choice_sort(list)))
    return new_list

print(app_list([6,3,5,87,69,52,4,16]))

  

冒泡排序

def maopao(lis):
    n = len(lis) - 1
    while n :
        i = 0

        while i < n:
            if lis[i] > lis[i+1]:
                lis[i],lis[i+1] = lis[i+1],lis[i]
            i += 1

        n -= 1

    return lis

print(maopao([6,3,5,87,69,52,4,16]))

  

posted on 2019-08-11 15:04  哎呀!土豆  阅读(179)  评论(0编辑  收藏  举报

导航