1. 程式人生 > >排序算法(三人組加上快排)

排序算法(三人組加上快排)

partition bsp 插入排序 urn while 選擇 and part quic

冒泡排序

def bubble_sort(li):
    for i in range(len(li)-1):
        for j in range(len(li)-i-1):
            if li[j]>li[j+1]:
                li[j],li[j+1]=li[j+1],li[j]
    return li
print(bubble_sort([112,1245325,2342,323]))

選擇排序

def select_sort(li):
    for i in range(len(li)-1):
        min_loc
=i for j in range(i+1,len(li)): if li[j]<li[min_loc]: min_loc=j if li[min_loc]!=i: li[i],li[min_loc]=li[min_loc],li[i] return li print(select_sort([11,23124,235,345,346,46]))

插入排序

def insert_sort(li):
    for i in range(1,len(li)):
        tmp
=li[i] j=i-1 while j>=0 and tmp<li[j]: li[j+1]=li[j] j=j-1 li[j+1]=tmp return li print(insert_sort([11231,423,5,436]))

快速排序

def quick_sort(data,left,right):
    if left < right:
        mid=partition(data,left,right)
        quick_sort(data,left,mid
-1) quick_sort(data,mid+1,right) return data def partition(data,left,right): tmp=data[left] while left < right: while left < right and data[right]>=tmp: right-=1 data[left]=data[right] while left < right and data[left] <=tmp: left+=1 data[right]=data[left] data[left]=tmp return left data=[11,243,25,534,6] print(quick_sort(data,0,len(data)-1))

排序算法(三人組加上快排)