实现简单选择排序、直接插入排序和冒泡排序。完整代码
时间: 2023-06-20 13:03:47 浏览: 83
以下是实现简单选择排序、直接插入排序和冒泡排序的完整 Python 代码:
```python
# 简单选择排序
def selection_sort(nums):
for i in range(len(nums)):
min_index = i
for j in range(i+1, len(nums)):
if nums[j] < nums[min_index]:
min_index = j
nums[i], nums[min_index] = nums[min_index], nums[i]
return nums
# 直接插入排序
def insertion_sort(nums):
for i in range(1, len(nums)):
j = i - 1
key = nums[i]
while j >= 0 and nums[j] > key:
nums[j+1] = nums[j]
j -= 1
nums[j+1] = key
return nums
# 冒泡排序
def bubble_sort(nums):
for i in range(len(nums)-1, 0, -1):
for j in range(i):
if nums[j] > nums[j+1]:
nums[j], nums[j+1] = nums[j+1], nums[j]
return nums
# 测试
nums = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
print(selection_sort(nums))
print(insertion_sort(nums))
print(bubble_sort(nums))
```
输出:
```
[1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
[1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
[1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
```
阅读全文