欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Python冒泡排序、快速排序、堆排序

程序员文章站 2023-11-24 19:07:10
Python冒泡排序、快速排序、堆排序冒泡排序def bubble_sort(array, n): for i in range(n): for j in range(1, n - i): if array[j - 1] > array[j]: array[j - 1], array[j] = array[j], array[j - 1]快速排序def quick_sort(array, l, r):...
  1. 冒泡排序
def bubble_sort(array, n):
    for i in range(n):
        for j in range(1, n - i):
            if array[j - 1] > array[j]:
                array[j - 1], array[j] = array[j], array[j - 1]
  1. 快速排序
def quick_sort(array, l, r):
    if l < r:
        q = partition(array, l, r)
        quick_sort(array, l, q - 1)
        quick_sort(array, q + 1, r)

def partition(array, l, r):
    x = array[r]
    i = l
    for j in range(l, r):
        if array[j] <= x:
            array[i], array[j] = array[j], array[i]
            i += 1
    array[i], array[r] = array[r], array[i]
    return i

  1. 堆排序
    注意堆排序外面还有一个在下面测试部分的循环。
# 堆排序
def heap_sort(array, n, length):
    l = 2*n + 1
    r = 2*n + 2
    if l <= length - 1:
        heap_sort(array, l, length)
    if r <= length - 1:
        heap_sort(array, r, length)

    if l >= length:
        return
    index = l
    if r < length and array[r] > array[l]:
        index = r

    if array[n] < array[index]:
        array[n], array[index] = array[index], array[n]
  1. 测试部分
if __name__ == '__main__':
    a = input("输入数组元素:").split(" ")
    a = list(map(int, a))
    b = a.copy()
    c = a.copy()

    # 冒泡排序
    bubble_sort(a, len(a))
    print(a)

    # 快速排序
    quick_sort(b, 0, len(b) - 1)
    print(b)

    # 堆排序
    for i in range(len(c)):
        heap_sort(c, 0, len(c) - i)
        c[0], c[len(c) - i - 1] = c[len(c) - i - 1], c[0]
    print(c)
  1. 测试结果
输入数组元素:4 8 3 6 7 1 5
[1, 3, 4, 5, 6, 7, 8]
[1, 3, 4, 5, 6, 7, 8]
[1, 3, 4, 5, 6, 7, 8]

Process finished with exit code 0

本文地址:https://blog.csdn.net/zndx18/article/details/107057196