#冒泡排序
def bubble_sort(l):
l_length = len(l)
for i in range(1, l_length - 1):
for j in range(0, l_length - 1):
if l[j] > l[j + 1]:
l[j], l[j + 1] = l[j + 1], l[j]
#选择排序
def selection_sort(l):
l_length = len(l)
for i in range(0, l_length -1):
n_min = i
for j in range(i+1, l_length):
if l[n_min] > l[j]:
n_min = j
if n_min != i:
l[i], l[n_min] = l[n_min], l[i]
#快速排序
def quick_sort(l, start=None, end=None):
l_length = len(l)
if start is None:
start = 0
if end is None:
end = l_length - 1
if start >= end:
return
k = l[start]
i, j = start, end
while i != j:
while i < j and l[j] >= k:
j -= 1
while i < j and l[i] <= k:
i += 1
if i < j:
l[i], l[j] = l[j], l[i]
l[start], l[i] = l[i], k
quick_sort(l, start, i - 1)
quick_sort(l, i + 1, end)
测试:
l1 = [randint(0, 100) for i in range(0, 20)]
l2 = copy(l1)
l3 = copy(l1)
print("before sort, l1: %s" % l1)
bubble_sort(l1)
print("after sort, l1: %s" % l1)
print("before sort, l2: %s" % l2)
selection_sort(l2)
print("after sort, l2: %s" % l1)
print("before sort, l3: %s" % l3)
quick_sort(l3)
print("after sort, l3: %s" % l3)
输出:
before sort, l1: [1, 49, 81, 84, 71, 54, 20, 48, 41, 13, 20, 31, 92, 43, 74, 100, 50, 86, 87, 69]
after sort, l1: [1, 13, 20, 20, 31, 41, 43, 48, 49, 50, 54, 69, 71, 74, 81, 84, 86, 87, 92, 100]
before sort, l2: [1, 49, 81, 84, 71, 54, 20, 48, 41, 13, 20, 31, 92, 43, 74, 100, 50, 86, 87, 69]
after sort, l2: [1, 13, 20, 20, 31, 41, 43, 48, 49, 50, 54, 69, 71, 74, 81, 84, 86, 87, 92, 100]
before sort, l3: [1, 49, 81, 84, 71, 54, 20, 48, 41, 13, 20, 31, 92, 43, 74, 100, 50, 86, 87, 69]
after sort, l3: [1, 13, 20, 20, 31, 41, 43, 48, 49, 50, 54, 69, 71, 74, 81, 84, 86, 87, 92, 100]
网友评论