# 冒泡排序两层循环,一直比较并交换
def bubble_sort(arr):
change_number = len(arr) - 1
for i in range(change_number):
for j in range(i + 1, change_number + 1):
if arr[i] > arr[j]:
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
return arr
# 选择排序与冒泡排序类似,区别在于选择排序并不是每次满足条件就交换,而是将最小值的索引存到
# k值中,在外层循环进行交换,这样可以减少交换次数,但是循环次数与冒泡排序相同
def selection_sort(arr):
change_number = len(arr)
for i in range(change_number):
k = i
for j in range(i + 1, change_number):
if arr[j] < arr[k]:
k = j
temp = arr[i]
arr[i] = arr[k]
arr[k] = temp
return arr
# 插入排序的特点是每次都与当前元素的前面元素们对比,满足条件时交换,从第二个数字开始循环
def insert_sort(arr):
change_number = len(arr)
for i in range(1, change_number):
j = i
while j > 0 and arr[j] < arr
python3 冒泡+选择+直接插入3种排序算法实现
最新推荐文章于 2020-02-06 15:55:55 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)