常见排序算法如下,包括其原理和对应的 Python 实现:
1. 冒泡排序
原理:比较相邻元素,如果顺序错误则交换,一轮结束后最大值会移动到末尾。重复直到所有元素有序。
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
# 测试
print(bubble_sort([64, 34, 25, 12, 22, 11, 90]))
2. 选择排序
:每次找到未排序部分的最小元素,放到已排序部分的末尾。
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
# 测试
print(selection_sort([64, 34, 25, 12, 22, 11, 90]))
3. 插入排序
原理:将当前元素插入到前面已排序部分的正确位置。
def insertion_sort(arr):
for i in range(1, len(arr)):
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
# 测试
print(insertion_sort([64, 34, 25, 12, 22, 11, 90]))
4. 快速排序
原理:选择一个基准值,将数组分成小于和大于基准值的两部分,递归处理。
def quick_sort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quick_sort(left) + middle + quick_sort(right)
# 测试
print(quick_sort([64, 34, 25, 12, 22, 11, 90]))
5. 归并排序
原理:分治法,将数组递归分成两部分,排序后合并。
def merge_sort(arr):
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = merge_sort(arr[:mid])
right = merge_sort(arr[mid:])
return merge(left, right)
def merge(left, right):
result = []
i = j = 0
while i < len(left) and j < len(right):
if left[i] < right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
result.extend(left[i:])
result.extend(right[j:])
return result
# 测试
print(merge_sort([64, 34, 25, 12, 22, 11, 90]))
6. 堆排序
原理:利用堆的特性,将最大或最小元素不断取出,调整剩余元素。
def heap_sort(arr):
def heapify(arr, n, i):
largest = i
left = 2 * i + 1
right = 2 * i + 2
if left < n and arr[left] > arr[largest]:
largest = left
if right < n and arr[right] > arr[largest]:
largest = right
if largest != i:
arr[i], arr[largest] = arr[largest], arr[i]
heapify(arr, n, largest)
n = len(arr)
for i in range(n//2 - 1, -1, -1):
heapify(arr, n, i)
for i in range(n-1, 0, -1):
arr[0], arr[i] = arr[i], arr[0]
heapify(arr, i, 0)
return arr
# 测试
print(heap_sort([64, 34, 25, 12, 22, 11, 90]))
7. 希尔排序
原理:基于插入排序,通过定义间隔逐步缩小排序范围,最终变成普通插入排序。
def shell_sort(arr):
n = len(arr)
gap = n // 2
while gap > 0:
for i in range(gap, n):
temp = arr[i]
j = i
while j >= gap and arr[j-gap] > temp:
arr[j] = arr[j-gap]
j -= gap
arr[j] = temp
gap //= 2
return arr
# 测试
print(shell_sort([64, 34, 25, 12, 22, 11, 90]))
每种排序算法适用于不同场景,具体选择视数据规模和特性而定。