1.冒泡排序 Bubble sort
优化后的冒泡排序
def bubbleSort(numlist,lenth):
for i in range(lenth):
flag = False #是否有数据交换标识
for j in range(lenth-i-1): # lenth-i-1是这个索引位置的数据已经是不用再去移动的了,已经是排好序的位置了
if numlist[j] > numlist[j+1]:
# temp = numlist[j]
# numlist[j] = numlist[j+1]
# numlist[j+1] = temp
numlist[j],numlist[j+1] = numlist[j+1],numlist[j]
flag = True
if flag == False: # 已经没有数据交换了
break
return listnum
2.插入排序 insertion sort
def insertionSort(num_list):
for i in range(1,len(num_list)):
current = num_list[i]
pre_index = i -1
while pre_index >= 0 and num_list[pre_index] > current:
num_list[pre_index+1] = num_list[pre_index]
pre_index -= 1
num_list[pre_index+1] = current
return num_list