首页 > 代码库 > Python三种排序算法

Python三种排序算法

冒泡排序:

def bubble_sort(lists):
    # 冒泡排序
    count = len(lists)
    for i in range(0, count):
        for j in range(i + 1, count):
            if lists[i] > lists[j]:
#判断后值是否比前置大,如果大就将其交换 lists[i], lists[j]
= lists[j], lists[i] return lists res=bubble_sort([1,209,31,4,555,6,765,9,5,4,7,89,6,5,34,3,57,96]) print(res)

快速排序:

def quick_sort(lists, left, right):
    # 快速排序
    if left >= right:
        return lists
    key = lists[left]
    low = left
    high = right
    while left < right:
        while left < right and lists[right] >= key:
            right -= 1
        lists[left] = lists[right]
        while left < right and lists[left] <= key:
            left += 1
        lists[right] = lists[left]
    lists[right] = key
    quick_sort(lists, low, left - 1)
    quick_sort(lists, left + 1, high)
    return lists

选择排序:

def select_sort(lists):
    # 选择排序
    count = len(lists)
    for i in range(0, count):
        min = i
        for j in range(i + 1, count):
            if lists[min] > lists[j]:
                min = j
        print("--------",lists[min], lists[i])
        lists[min], lists[i] = lists[i], lists[min]
        print(lists[min], lists[i])
    return lists

res=select_sort([1,209,31,4,555,6,765,9,5,4,7,89,6,5,34,3,57,96])
print(res)

 

Python三种排序算法