排序算法

2019-03-31  本文已影响0人  临渊如峙

一、冒泡排序

def bubble_sort(ls):
    length = len(ls)
    # 比较趟数
    for j in range(length):
        # 每趟的比较次数
        for i in range(j):
            if ls[i] >= ls[i + 1]:
                ls[i], ls[i + 1] = ls[i + 1], ls[i]
    return ls

二、选择排序

def select_sort(ls):
    length = len(ls)
    for i in range(0, length-1):
        smallest = i
        for j in range(i+1, length):
            if ls[j] < ls[smallest]:
                ls[j], ls[smallest] = ls[smallest], ls[j]
    return ls

三、快速排序

def partiton(ls, low, high):
    key = ls[low]
    while low < high:
        while low < high and ls[high] >= key:
            high -= 1
        if low < high:
            ls[low], ls[high] = ls[high], ls[low]

        while low < high and ls[low] < key:
            low += 1
        if low < high:
            ls[high], ls[low] = ls[low], ls[high]

    return low

def quickSort(ls, low, high):
    if low >= high:
        return
    center = partiton(ls, low, high)
    quickSort(ls, low, center - 1)
    quickSort(ls, center + 1, high)
    return ls
上一篇 下一篇

猜你喜欢

热点阅读