from random import shuffle
def bubble_sort(seq):
for i in range(len(seq)):
for j in range(len(seq)-1, i, -1):
if seq[j] < seq[j-1]:
tmp = seq[j]
seq[j] = seq[j-1]
seq[j-1] = tmp
def insert_sort(seq):
seq_len = len(seq)
if seq_len == 1 or seq_len == 0:
return
for i in range(1, seq_len):
for j in range(0, i):
if seq[i] < seq[j]:
tmp = seq[i]
seq.pop(i)
seq.insert(j, tmp)
def select_sort(seq):
for i in range(len(seq)):
min_index = i
for j in range(i+1, len(seq)):
if seq[min_index] > seq[j]:
min_index = j
tmp = seq[min_index]
seq[min_index] = seq[i]
seq[i] = tmp
if __name__ == '__main__':
seq = range(10)
shuffle(seq)
print seq
bubble_sort(seq)
print seq
shuffle(seq)
print seq
insert_sort(seq)
print seq
shuffle(seq)
print seq
select_sort(seq)
print seq
python写基础排序:冒泡、插入、选择
最新推荐文章于 2022-12-15 19:20:22 发布