排序算法

1. 冒泡排序
def bubble_sort(lst):
    length = len(lst)
    for i in range(length - 1):
        for j in range(length - i - 1):
            if lst[j] > lst[j + 1]:
                lst[j], lst[j + 1] = lst[j + 1], lst[j]
View Code

2. 快速排序

def quick_sort(lst, le, ri):
    if le >= ri:
        return
    left, right = le, ri
    pivot = lst[left]
    while left < right:
        while left < right and lst[right] >= pivot:
            right -= 1
        if left < right:
            lst[left] = lst[right]
        while left < right and lst[left] <= pivot:
            left += 1
        if left < right:
            lst[right] = lst[left]
        if left >= right:
            lst[left] = pivot
    quick_sort(lst, le, right - 1)
    quick_sort(lst, right + 1, ri)
View Code

3. 插入排序

def insert_sort(lst, length):
    for i in range(1, length):
        temp = lst[i]
        j = i - 1
        while j >= 0 and lst[j] > temp:
            lst[j + 1] = lst[j]
            j -= 1
        lst[j + 1] = temp
View Code

 

posted @ 2022-07-02 16:10  xuqidong  阅读(10)  评论(0编辑  收藏  举报