排序算法
built-in 排序函数
array = [8, 2, 6, 4, 5]
sorted(array) # [2, 4, 5, 6, 8]
冒泡排序
def bubble_sort(array):
n = len(array)
for i in range(n):
# Create a flag that will allow the function to
# terminate early if there's nothing left to sort
already_sorted = True
# Start looking at each item of the list one by one,
# comparing it with its adjacent value. With each
# iteration, the portion of the array that you look at
# shrinks because the remaining items have already been
# sorted.
for j in range(n - i - 1):
if array[j] > array[j + 1]:
# If the item you're looking at is greater than its
# adjacent value, then swap them
array[j], array[j + 1] = array[j + 1], array[j]
# Since you had to swap two elements,
# set the `already_sorted` flag to `False` so the
# algorithm doesn't finish prematurely
already_sorted = False
# If there were no swaps during the last iteration,
# the array is already sorted, and you can terminate
if already_sorted:
break
return array
现在一步一步去看此排序算法程序做了什么
- 代码开始时比较第一个元素【8】和它相邻的元素【2】从【8】>【2】值进行交换 结果是[2, 8, 6, 4, 5].
- 算法之后比较第二个元素【8】和相邻的元素【6】从【8】>【6】值交换 结果为[2, 6, 8, 4, 5].
- 之后以此类推
- 最终 算法比较到这 [2, 6, 4, 5, 8].时 算法完成了第一步遍历数组(i=0)
- 第二步(i=1) 列表的最后一个元素已经就位 接下来注意力集中在剩下四个元素身上 [2, 6, 4, 5] 在这一步的最后值6已经找到了他的位置第三步就是5 以此类推