参考博客:https://www.cnblogs.com/onepixel/articles/7674659.html
说的很详细哈
先摆出一些重要概念:
稳定:如果a原本在b前面,而a=b,排序之后a仍然在b的前面。
不稳定:如果a原本在b的前面,而a=b,排序之后 a 可能会出现在 b 的后面。
时间复杂度:对排序数据的总的操作次数。反映当n变化时,操作次数呈现什么规律。
空间复杂度:是指算法在计算机内执行时所需存储空间的度量,它也是数据规模n的函数。
排序的分类:
一个个来,我们先讲交换排序。
一、交换排序之冒泡排序
依据冒泡排序的概念,用python实现的代码:
def bubble_sort(input_arr):
if not input_arr or len(input_arr) < 1:
return False
length = len(input_arr)
bottom_idx = 0
while bottom_idx < length - 1:
i = length - 1
while i > bottom_idx:
if input_arr[i] < input_arr[i - 1]:
tmp = input_arr[i]
input_arr[i] = input_arr[i - 1]
input_arr[i - 1] = tmp
i -= 1
bottom_idx += 1
return
冒泡优化点1:如果一趟比较中,没有任何位置交换,则直接结束,这说明序列已经按照正确的顺序排列:
def bubble_sort_opt_1(input_arr):
"""
冒泡优化点1:如果一趟比较中,没有任何位置交换,则直接结束,这说明序列已经按照正确的顺序排列
:param input_arr:
:return:
"""
if not input_arr or len(input_arr) < 1:
return False
length = len(input_arr)
bottom_idx = 0
while bottom_idx < length - 1:
i = length - 1
is_exchange = False
while i > bottom_idx:
if input_arr[i] < input_arr[i - 1]:
tmp = input_arr[i]
input_arr[i] = input_arr[i - 1]
input_arr[i - 1] = tmp
is_exchange = True
i -= 1
if nois_exchange:
break
bottom_idx += 1
return
冒泡优化点2:如果一趟比较中,有位置交换,则标记第一次交换位置的地方,说明在这次交换之前的序列都是有序的。下一次循环直接从这个标记的位置开始
def bubble_sort_opt_2(input_arr):
"""
冒泡优化点2:如果一趟比较中,有位置交换,则记录第一次交换位置的地方,说明这次交换之前的序列都是有序的,下一次循环直接从这个位置开始
:param input_arr:
:return:
"""
if not input_arr or len(input_arr) < 1:
return False
length = len(input_arr)
bottom_idx = 0
top_idx = length - 1
while bottom_idx < top_idx:
i = top_idx
is_exchange = False
# 用来标记第一次交换的位置
next_i = -1
while i > bottom_idx:
if input_arr[i] < input_arr[i - 1]:
tmp = input_arr[i]
input_arr[i] = input_arr[i - 1]
input_arr[i - 1] = tmp
is_exchange = True
if next_i < 0:
next_i = i - 1
i -= 1
if not is_exchange:
break
bottom_idx += 1
if next_i > 0:
top_idx = next_i
else:
top_idx -= 1
return