请用分别用冒泡法和快速排序法排序
时间: 2023-05-26 12:02:45 浏览: 89
以下是Python代码示例:
使用冒泡法排序:
```python
def bubble_sort(arr):
n = len(arr)
for i in range(n-1):
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
arr = [64, 34, 25, 12, 22, 11, 90]
print("原始数组:", arr)
print("冒泡排序后:", bubble_sort(arr))
```
输出结果为:
```
原始数组: [64, 34, 25, 12, 22, 11, 90]
冒泡排序后: [11, 12, 22, 25, 34, 64, 90]
```
使用快速排序法排序:
```python
def quick_sort(arr):
if len(arr) <= 1:
return arr
else:
pivot = arr[0]
less = [x for x in arr[1:] if x <= pivot]
greater = [x for x in arr[1:] if x > pivot]
return quick_sort(less) + [pivot] + quick_sort(greater)
arr = [64, 34, 25, 12, 22, 11, 90]
print("原始数组:", arr)
print("快速排序后:", quick_sort(arr))
```
输出结果为:
```
原始数组: [64, 34, 25, 12, 22, 11, 90]
快速排序后: [11, 12, 22, 25, 34, 64, 90]
```
阅读全文