常见排序算法

常见排序算法

  • 常见排序算法效率
  • 冒泡排序
def maopao(alist):
    for i in range(len(alist)):
        for j in range(len(alist)-1-i):
            if alist[j] > alist[j+1]:
                alist[j], alist[j+1] = alist[j+1], alist[j]
    return alist
  • 插入排序
def insert_sort(alist):
    for i in range(1, len(alist)):
        for j in range(i, 0, -1):
            if alist[j] < alist[j-1]:
                alist[j], alist[j-1] = alist[j-1], alist[j]
    return alist
  • 选择排序
def select_sort(alist):
    for i in range(len(alist)-1):
        min_index = i
        for j in range(i+1, len(alist)):
            if alist[j] < alist[min_index]:
                min_index = j
        if min_index != i:
            alist[i], alist[min_index] = alist[min_index], alist[i]
    return alist

  • 快速排序
def quick_sort(alist, start, end):
    mid = alist[start]
    low = start
    high = end

    if low >= high:
        return

    while low < high:
        while low < high and alist[high] >= mid:
            high -= 1
        alist[low] = alist[high]
        while low < high and alist[low] <= mid:
            low += 1
        alist[high] = alist[low]

    alist[low] = mid
    quick_sort(alist, start, low-1)
    # quick_sort(alist, 0, low-1) #会报错
    quick_sort(alist, low+1, len(alist)-1)
    return alist

  • 归并排序
  • 希尔排序

你可能感兴趣的:(数据结构与算法,排序算法)