1. 程式人生 > >用python實現選擇排序法、氣泡排序法、插入排序法

用python實現選擇排序法、氣泡排序法、插入排序法

氣泡排序法

l = [10, 1, 18, 30, 23, 12, 7, 5, 18, 17]
for n in range(len(l)-1):
    for i in range(len(l)-n-1):
        if l[i] > l[i+1]:
            l[i],l[i+1] = l[i+1],l[i]
print(l)

選擇排序法

l = [10, 1, 18, 30, 23, 12, 7, 5, 18, 17]
for n in range(len(l)-1):
    for i in range(n,len(l)):
        if l[i] < l[n]:
            tmp = l[n]
            l[n] = l[i]
            l[i] = tmp
print(l)

插入排序法

l = [10, 1, 18, 30, 23, 12, 7, 5, 18, 17]
for i in range(1,len(l)):
    if l[i] < l[i-1]:
        t = l[i]
        j = i-1
        while j >= 0 :
            if l[j] > t:
                l[j+1] = l[j]
                l[j] = t
                print(l)
            j -= 1
print(l)