冒泡排序bubble_sort

def bubble_sort(list):
for i in range(0,len(list)-1):
flag = 0
for j in range(0,len(list)-1-i):
if list[j] > list[j+1]:
list[j], list[j+1] = list[j+1], list[j]
flag += 1
if flag == 0:
return list
return list

sorted_list = bubble_sort([1,2,5,4,3])
print(sorted_list)

选择排序selected_sort

def selected_sort(list):
min_index = 0
for i in range(0,len(list)-1):
for j in range(i,len(list)):
if list[j] < list[min_index]:
min_index = j
list[i], list[min_index] = list[min_index], list[i]
min_index = i + 1
return list

sorted_list = selected_sort([1,8,6,4,5])
print(sorted_list)

插入排序inserted_sort

def inserted_sort(list):
for i in range(1,len(list)):
while i > 0:
if list[i] < list[i-1]:
list[i], list[i-1] = list[i-1], list[i]
i -= 1
else:
break
return list

sorted_list = inserted_sort([1,7,3,8,5])
print(sorted_list)

希尔排序shell_sort

def shell_sort(list):
gap = len(list) // 2
while gap >= 1:
for i in range(gap,len(list)):
while i > 0:
if list[i] < list[i-gap]:
list[i], list[i-gap] = list[i-gap], list[i]
i -= gap
else:
break
gap //= 2
return list

sorted_list = shell_sort([1,7,3,9,5,2])

快速排序quick_sort

def quick_sort(list,head,tail):
if head >= tail:
return list
pivot = list[head]
low = head
high = tail
while low != high:
while low < high and list[high] > pivot:
high -= 1
list[low] = list[high]

while low < high and list[low] < pivot:
low += 1
list[high] = list[low]
list[low] = pivot
quick_sort(list,head,low-1)
quick_sort(list,low+1,tail)
return list

sorted_list = quick_sort([1,7,3,9,5,2],0,5)
print(sorted_list)

归并排序merge_sort

def merge_sort(list):
n = len(list)
if n <= 1:
return list
pivot_index = n // 2
first_list = merge_sort(list[0:pivot_index])
second_list = merge_sort(list[pivot_index:])

first_index = 0
second_index = 0
res = []
while first_index < len(first_list) and second_index < len(second_list):
if first_list[first_index] < second_list[second_index]:
res.append(first_list[first_index])
first_index += 1
else:
res.append(second_list[second_index])
second_index += 1
res += first_list[first_index:]
res += second_list[second_index:]
return res

sorted_list = merge_sort([1,7,3,9,5,2])
print(sorted_list)