python实现排序算法

时间:2021-02-24 02:07:27
冒泡排序 
import random
def BubbleSort(num):
    n=len(num)
    for i in range(0,n):
        for j in range(i,n):
            if num[i]>=num[j]:
                num[i],num[j]=num[j],num[i]
    return num
 
选择排序
def SelectSort(num):
    for i in range(0,len(num)):
        mindex=i
        for j in range(i,len(num)):
            if num[mindex]>num[j]:
                mindex=j
        num[mindex],num[i]=num[i],num[mindex]
    return num
 
插入排序
def InsertSort(num):
    for i in range(1,len(num)):
        j=i-1
        tmp=num[i]
        while j>0 and tmp<num[j]:
            num[j+1]=num[j]            
            j-=1
        num[j]=tmp
    return num
 
归并排序
def MergerSort(num):
    if len(num)<=1:
        return num
    left=MergerSort(num[:len(num)/2])
    right=MergerSort(num[len(num)/2:])
    result=[]
    while len(left)>0 and len(right)>0:
        if left[0]>right[0]:
            result.append(right.pop(0))
        else:
            result.append(left.pop(0))
    if len(left)>0:
        result.extend(MergerSort(left))
    else:
        result.extend(MergerSort(right))
    return result
 
快速排序
def QuickSort(num):
    if len(num)<=1:
        return num
    greater=[]
    less=[]
    p=num.pop(random.randint(0,len(num)-1))
    for item in num:
        if item < p:
            less.append(item)
        else:
            greater.append(item)
    return QuickSort(less)+[p]+QuickSort(greater)