1.冒泡排序
作为常见的排序方法之一,冒泡排序的原理很简单
1.从一组数据的下标索引为0开始,每次与下一位数据做对比,如果比下一位数据要大,则交换两数据的位置,将所有元素按顺序重复这个过程,就实现了一次循环。
2.一次循环后会将最大值放到最末尾,所以在下一次整体循环的时候,只需重复上述步骤到第n-2位置
3.重复直到排序完成
最坏时间复杂度O(N²)
最优时间复杂度O(N)
def bubble_sort(alist):
for j in range(len(alist) - 1):
count = 0
for i in range(0, len(alist) - 1 - j):
if alist[i] > alist[i + 1]:
alist[i], alist[i + 1] = alist[i + 1], alist[i]
count += 1
if 0 == count:
return
return alist
if __name__ == '__main__':
a = [1, 3, 5, 7, 2]
print(a)
print(bubble_sort(a))
[1, 3, 5, 7, 2]
[1, 2, 3, 5, 7]
2.选择排序
选择排序的原理如下
1.从数组一端开始,每次循环选出当前遍历中最小的数据,放入整组数据的最左端
2.重复上述步骤,直至排序完成
最坏时间复杂度和最优时间复杂度均为O(N²)
def select_sort(alist):
n = len(alist)
for j in range(n - 1):
min_index = j
for i in range(1 + j, n):
if alist[min_index] > alist[i]:
min_index = i
alist[j], alist[min_index] = alist[min_index], alist[j]
return alist
if __name__ == '__main__':
a = [1, 3, 2, 7, 2]
print(a)
print(select_sort(a))
[1, 3, 2, 7, 2]
[1, 2, 2, 3, 7]
3.插入排序法
进本原理
1.从一数组左端第二个元素开始,用此元素与左边元素作比较,如果此值较小,则与比较值交换位置。换位置后重复上述步骤,直至一次循环完成
2.起始位置右移一位,重复循环,直至遍历所有数组内容。
最优时间复杂度O(N)
最差时间复杂度O(N²)
def insert_sort(alist):
n = len(alist)
for j in range(1, n):
i = j
while i > 0:
if alist[i] < alist[i - 1]:
alist[i], alist[i - 1] = alist[i - 1], alist[i]
i -= 1
return alist
if __name__ == '__main__':
a = [1, 3, 2, 7, 2]
print(a)
print(insert_sort(a))
[1, 3, 2, 7, 2]
[1, 2, 2, 3, 7]
4.希尔排序
希尔排序是插入排序的特殊化,他会使用到步长操作。
1.步长选为数据长度的2分之一(取整),使每个部分对应位置的数组进行排列
2.步长继续取半,直至步长为1,排序结束
最坏时间复杂度O(N²)
def shell_sort(alist):
n = len(alist)
gap = n // 2
while gap > 0:
for j in range(gap, n):
i = j
while i > 0:
if alist[i] < alist[i - gap]:
alist[i], alist[i - gap] = alist[i - gap], alist[i]
i -= gap
gap //= 2
return alist
if __name__ == '__main__':
a = [1, 9, 3, 5, 7, 2]
print(a)
print(shell_sort(a))
[1, 9, 3, 5, 7, 2]
[1, 2, 3, 5, 7, 9]