# python: 经典排序 汇总

## 冒泡排序

```def bubble_sort(x):
for i in range(len(x)):
for j in range(1, len(x)-i):
if x[j-1] > x[j]:
x[j-1], x[j] = x[j], x[j-1]
return x```

## 插入排序

```def insert_sort(x):
for i in range(len(x)):
for j in range(i):
if x[i] < x[j]:
tmp = x[i]
for p in range(i, j, -1):
x[p] = x[p-1]
x[j] = tmp
return x```

## 选择排序

```def select_sort(x):
for i in range(len(x)):
for j in range(i+1, len(x)):
if x[i] > x[j]:
x[i], x[j] = x[j], x[i]
return x```

## 归并排序

```def merge(left, right):
i, j, res = 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:] or right[j:]
return res
def merge_sort(x):
if len(x) <= 1:
return x
mid = len(x) // 2
left = merge_sort(x[:mid])
right = merge_sort(x[mid:])
return merge(left, right)```

## 快速排序

```def quick_sort(x, low, high):
if low >= high:
return x
base, left, right = x[low], low, high
while left < right:
while left < right and x[right] >= base:
right -= 1
x[left] = x[right]
while left < right and x[left] <= base:
left += 1
x[right] = x[left]
x[left] = base
quick_sort(x, low, left-1)
quick_sort(x, left+1, high)
return x```

0 条评论