python排序算法

2019-07-31  本文已影响0人  是东东

参考十大经典排序算法(动图演示)

1、 冒泡排序(Bubble Sort)
def bubble_sort(arr):
    for i in range(len(arr) - 1):
        for j in range(i + 1, len(arr)):
            if arr[i] > arr[j]:
                arr[i], arr[j] = arr[j], arr[i]
    return arr
2、选择排序(Selection Sort)
def seletion_sort(arr):
    for i in range(len(arr)-1):
        i_min = i
        for j in range(i+1, len(arr)):
            if arr[i_min] > arr[j]:
                i_min = j
        if i != i_min:
            arr[i_min], arr[i] = arr[i], arr[i_min]
    return arr
3、插入排序(Insertion Sort)
def seletion_sort(arr):
    for i in range(1, len(arr)):
        pre = i - 1
        current = arr[i]
        while pre >= 0 and arr[pre] > current:
            arr[pre+1] = arr[pre]
            pre -= 1
        arr[pre+1] = current
    return arr
上一篇下一篇

猜你喜欢

热点阅读