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

python:4种基本排序算法

程序员文章站 2023-01-28 17:54:19
1.冒泡排序 # -*- coding:utf-8 -*- def bubble_sort(A): for i in range(len(A)-1):...

1.冒泡排序

# -*- coding:utf-8 -*-


def bubble_sort(A):
    for i in range(len(A)-1):  # 决定进行的轮数
        for j in range(0, len(A)-i-1):  # 列表下标
            if A[j] > A[j+1]:
                A[j+1], A[j] = A[j], A[j+1]
    return A


A = [0, 5, 4, 3, 2, 1]
print(bubble_sort(A))

2.快速排序

# -*- coding:utf-8 -*-


def partition(A, low, high):
    pivot = A[low]
    while low < high:
        while low < high and A[high] >= pivot:
            high -= 1
        A[low] = A[high]
        while low < high and A[low] <= pivot:
            low += 1
        A[high] = A[low]
    A[low] = pivot
    return low


def quick_sort(A, low, high):
    if low < high:
        pivot = partition(A, low, high)
        print(A, low, high)
        quick_sort(A, low, pivot-1)
        quick_sort(A, pivot+1, high)
    return A


A = [3, 5, 4, 8, 2, 1]
print(quick_sort(A, 0, 5))

3.归并排序

# -*- coding:utf-8 -*-


def merge_sort(A):
    if len(A) == 1:
        return A
    mid = len(A)//2
    left = merge_sort(A[:mid])
    right = merge_sort(A[mid:])

    return merge(left, right)


def merge(left, right):
    result = []
    while len(left) > 0 and len(right) > 0:
        if left[0] < right[0]:
            result.append(left.pop(0))
        else:
            result.append(right.pop(0))
    result += left
    result += right
    return  result


A = [3, 5, 4, 8, 2, 1]
print(merge_sort(A))

4. 插入排序

# -*- coding:utf-8 -*-


def insert_sort(A):
    for i in range(1, len(A)):
        j = i-1
        if A[i] < A[j]:
            temp = A[i]
            A[i] = A[j]
            j = j-1
            while j >= 0 and A[j] > temp:
                A[j+1] = A[j]
                j -= 1
            A[j+1] = temp
    return A


A = [3, 5, 4, 8, 2, 1]
print(insert_sort(A))