写一个python排序程序代码
时间: 2023-10-12 14:05:09 浏览: 76
以下是Python实现的几种常见排序算法:
1. 冒泡排序
```python
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
return arr
```
2. 选择排序
```python
def selection_sort(arr):
n = len(arr)
for i in range(n):
min_index = i
for j in range(i+1, n):
if arr[j] < arr[min_index]:
min_index = j
arr[i], arr[min_index] = arr[min_index], arr[i]
return arr
```
3. 插入排序
```python
def insertion_sort(arr):
n = len(arr)
for i in range(1, n):
key = arr[i]
j = i - 1
while j >= 0 and arr[j] > key:
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key
return arr
```
4. 快速排序
```python
def quick_sort(arr):
if len(arr) <= 1:
return arr
pivot = arr[0]
left, right = [], []
for i in range(1, len(arr)):
if arr[i] < pivot:
left.append(arr[i])
else:
right.append(arr[i])
return quick_sort(left) + [pivot] + quick_sort(right)
```
5. 归并排序
```python
def merge_sort(arr):
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left, right = arr[:mid], arr[mid:]
return merge(merge_sort(left), merge_sort(right))
def merge(left, right):
res = []
i, j = 0, 0
while i < len(left) and j < len(right):
if left[i] < right[j]:
res.append(left[i])
i += 1
else:
res.append(right[j])
j += 1
res += left[i:]
res += right[j:]
return res
```
以上是Python实现的几种常见排序算法。
阅读全文