常见排序算法 :插入,选择,冒泡
1.插入排序
- 时间复杂度:O(n²)
- 空间复杂度:O(1)
- 稳定性:稳定
# 插入排序 def insert(list): for i in range(len(list)): for j in range(i): if list[i] < list[j]: list.insert(j,list.pop(i)) break return list list = [2, 6, 4, 3] if __name__ == '__main__': insert(list) print(list)
2.选择排序
- 时间复杂度:O(n²)
- 空间复杂度:O(1)
- 稳定性:不稳定
# 选择排序 def select(list): for i in range(len(list)): x = i # i是最小下表 for j in range(i, len(list)): if list[j] < list[i]: x = j list[i], list[x] = list[x], list[i] return list list = [2, 6, 4, 3] if __name__ == '__main__': select(list) print(list)
3.冒泡排序
- 时间复杂度:O(n²)
- 空间复杂度:O(1)
- 稳定性:稳定
# 冒泡排序 def bubblesort(list): for i in range(len(list)): for j in range(i, len(list)): if list[i] > list[j]: list[i], list[j] = list[j], list[i] return list if __name__ =='__main__': list = [7.8, 5.3, 34, 2.5, 91] bubblesort(list) print(list)