对用随机函数产生的10个数,按从小到大的顺序排序,分别用冒泡排序、选择排序、插入排序来实现。 排序用函数来编写;传递数组,可以是数组元素,可以整个数组
时间: 2023-06-11 12:09:03 浏览: 77
新建文件夹 (3).zip_从小到大排序_冒泡法_文件夹123456789
5星 · 资源好评率100%
冒泡排序的实现:
```python
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
return arr
```
选择排序的实现:
```python
def selection_sort(arr):
n = len(arr)
for i in range(n):
min_idx = i
for j in range(i+1, n):
if arr[j] < arr[min_idx]:
min_idx = j
arr[i], arr[min_idx] = arr[min_idx], arr[i]
return arr
```
插入排序的实现:
```python
def insertion_sort(arr):
n = len(arr)
for i in range(1, n):
key = arr[i]
j = i-1
while j >= 0 and key < arr[j]:
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key
return arr
```
示例代码:
```python
import random
arr = [random.randint(1, 100) for i in range(10)]
print("Original array:", arr)
print("Bubble sort:", bubble_sort(arr[:]))
print("Selection sort:", selection_sort(arr[:]))
print("Insertion sort:", insertion_sort(arr[:]))
```
阅读全文