常见排序算法 Python实现

冒泡排序

def bubbleSort(lst):
    for n in range(len(lst)-1,0,-1):
        for i in range(n):
            if lst[i] > lst[i+1]:
                temp = lst[i]
                lst[i] = lst[i+1]
                lst[i+1] = temp

选择排序

def selectionSort(lst):
    for n in range(len(lst) - 1, 0, -1):
        max = n
        for i in range(n+1):
            if lst[i]>lst[max]:
                max = i
        temp = lst[n]
        lst[n] = lst[max]
        lst[max] = temp

插入排序

def insertSort(lst):
    for n in range(1,len(lst)):
        value = lst[n]
        i = n-1
        while i > -1 and lst[i]>value:
            lst[i+1] = lst[i]
            i -= 1
        lst[i+1] = value

归并排序

def mergeSort(lst):
    if len(lst)>1:
        mid = len(lst)//2
        lefthalf = lst[:mid]
        righthalf = lst[mid:]

        mergeSort(lefthalf)
        mergeSort(righthalf)

        i,j,k = 0,0,0
        while i < len(lefthalf) and j < len(righthalf):
            if lefthalf[i] < righthalf[j]:
                lst[k] = lefthalf[i]
                i += 1
            else:
                lst[k] = righthalf[j]
                j += 1
            k += 1

        while i < len(lefthalf):
            lst[k] = lefthalf[i]
            i += 1
            k += 1

        while j < len(righthalf):
            lst[k] = righthalf[j]
            j += 1
            k += 1

快速排序

def quickSort(lst,l,r):
    if l >= r:
        return
    low,high = l,r
    temp = lst[low]
    while low < high:
        while low < high and lst[high] >= temp:
            high -= 1
        lst[low] = lst[high]
        while low < high and lst[low] <= temp:
            low += 1
        lst[high] = lst[low]
    lst[low] = temp
    quickSort(lst,l,low-1)
    quickSort(lst,low+1,r)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值