选择排序:
def selectSort(l):
size = len(l)
for i in range(0,size):
max = l[i]
index = i
for j in range(i,size):
if l[j] > max:
max = l[j]
index = j
temp = l[i]
l[i] = max
l[index] = temp
print(l)
执行结果:
>>> s = [5,8,55,3,9,3,6,5,2]
>>> selectSort(s)
[55, 8, 5, 3, 9, 3, 6, 5, 2]
[55, 9, 5, 3, 8, 3, 6, 5, 2]
[55, 9, 8, 3, 5, 3, 6, 5, 2]
[55, 9, 8, 6, 5, 3, 3, 5, 2]
[55, 9, 8, 6, 5, 3, 3, 5, 2]
[55, 9, 8, 6, 5, 5, 3, 3, 2]
[55, 9, 8, 6, 5, 5, 3, 3, 2]
[55, 9, 8, 6, 5, 5, 3, 3, 2]
[55, 9, 8, 6, 5, 5, 3, 3, 2]
插入排序:
def insertSort(l):
size = len(l)
for i in range(1,size):
fv = l[i]
j = i
while j >= 1:
if fv < l[j-1]:
l[j] = l[j-1]
else:
break
j = j - 1
l[j] = fv
print(l)
例子:
>>> l = [5,8,55,3,9,3,6,5,2]
>>> insertSort(l)
[5, 8, 55, 3, 9, 3, 6, 5, 2]
[5, 8, 55, 3, 9, 3, 6, 5, 2]
[3, 5, 8, 55, 9, 3, 6, 5, 2]
[3, 5, 8, 9, 55, 3, 6, 5, 2]
[3, 3, 5, 8, 9, 55, 6, 5, 2]
[3, 3, 5, 6, 8, 9, 55, 5, 2]
[3, 3, 5, 5, 6, 8, 9, 55, 2]
[2, 3, 3, 5, 5, 6, 8, 9, 55]