# 从第二个数开始和前面的数比较,插入合适位置
def insertion_sot(array):
for index in range(1,len(array)):
position = index
temp_value = array[index]
while position > 0 and array[position-1]>temp_value:
array[position]=array[position-1]
position=position-1
array[position]=temp_value
return array
list = insertion_sort([1,3,7,6,8,2])
print(list)
冒泡排序O(n^2)
# 两两比较,将最大值移到最后面
def bubble_sort(list):
unsort_until_index = len(list)-1
sorted=False
while not sorted:
sorted = True
for i in range(unsort_until_index):
if list[i]>list[i+1]:
sorted=False
list[i],list[i+1] = list[i+1],list[i]
unsort_until_index = unsort_until_index-1
list = [65,55,45,35,1,2,6,2]
bubble_sort(list)
print(list)
选择排序O(n^2)
# 时间复杂度是冒泡排序的一半,即O(n^2/2)
# 存储最小值并和每一个值比较,一轮比较后,将最小值和无序列表中第一个值交换位置
def selectionSort(list):
for i in range(len(list)):
for j in range(i+1,len(list)):
tmp = i
if list[tmp] > list[j]:
tmp = j
list[i],list[tmp] = list[tmp],list[i]
list = [65,50,55,45,35,1,2,6,2]
selectionSort(list)
print(list)