冒泡排序的四种解法
1 . 常规冒泡
def bubble_sort_1(array=[]):
for i in range(len(array) - 1):
for j in range(len(array) - i - 1):
if array[j] > array[j + 1]:
temp = array[j]
array[j] = array[j + 1]
array[j + 1] = temp
测试
my_array = list([3, 4, 14, 1, 5, 6, 7, 8, 1, -1, 0, 9, 11])
bubble_sort_v1(my_array)
print(my_array)
2 . 检查已经有序时就终止循环
def bubble_sort_2(array=[]):
for i in range(len(array) - 1):
is_sorted = True
for j in range(len(array) - i - 1):
if array[j] > array[j + 1]:
temp = array[j]
array[j] = array[j + 1]
array[j + 1] = temp
is_sorted = False
if is_sorted:
break
3 . 界定有序边界,只排序无序部分
def bubble_sort_v3(array=[]):
sorted_border = len(array) - 1
last_sorted_index = 0
for i in range(len(array) - 1):
is_sorted = True
for j in range(sorted_border):
if array[j] > array[j + 1]:
temp = array[j]
array[j] = array[j + 1]
array[j + 1] = temp
is_sorted = False
last_sorted_index = j
sorted_border = last_sorted_index
if is_sorted:
break
4 . 针对前半段大部分有序,后半段无序情况(鸡尾酒排序)
def cock_tail_sort(array=[]):
for i in range(len(array) - 1):
is_sorted = True
for j in range(len(array) - i - 1):
if array[j] > array[j + 1]:
temp = array[j]
array[j] = array[j + 1]
array[j + 1] = temp
is_sorted = False
if is_sorted:
break
is_sorted = True
for k in range(len(array) - i - 1, i, -1):
if array[k] < array[k - 1]:
temp = array[k]
array[k] = array[k - 1]
array[k - 1] = temp
is_sorted = False
if is_sorted:
break
测试
my_array = list([2, 3, 4, 5, 6, 7, 8, 1])
cock_tail_sort(my_array)
print(my_array)