目录
一、插入排序
二、冒泡排序
三、快排(递归)
四、选择排序
生成一个长度为10的范围在0~20的随机数组
import random
temp_list = []
while True:
num = random.randint(0, 20)
if num not in temp_list:
temp_list.append(num)
if len(temp_list) == 10:
break
print temp_list
一、插入排序
def insert(list):
length = len(list)
for i in range(1, length):
temp = list[i]
j = i - 1
while j >= 0 and list[j] > temp:
list[i], list[j] = list[j], list[i]
print 'j:', j, list
i = j
j -= 1
print "finished:", list
二、冒泡排序
def bubble_sort(list):
length = len(list) - 1
for i in range(length):
flag = True # 优化
for j in range(length - i):
if list[j] > list[j+1]:
list[j], list[j+1] = list[j+1], list[j]
flag = False
print "::j", j, list
print "::i", i, list
if flag:
break
三、快排(递归)
def kuaipai(list):
if list == []:
return []
else:
temp = list[0]
left = [i for i in list if i < temp]
right = [i for i in list if i > temp]
return left + [temp] + right
四、选择排序
def choose(list):
length = len(list)
for i in range(length):
x = i
for j in range(i, length):
if list[i] > list[j]:
x = j # 每次选出最小值
list[i], list[x] = list[x], list[i]
print list