写实验程序,完成分别采用以下算法完成的整数序列递增排序算法,要求输出每一趟排序的结果:直接插入排序、希尔排序、冒泡排序、快速排序、简单选择排序、堆排序和归并排序python
时间: 2023-08-26 14:03:47 浏览: 91
实现各种排序.txt
好的,下面给出每种排序算法的Python实现:
### 直接插入排序
def insert_sort(arr):
n = len(arr)
for i in range(1, n):
j = i
while j > 0 and arr[j] < arr[j-1]:
arr[j], arr[j-1] = arr[j-1], arr[j]
j -= 1
print(arr)
### 希尔排序
def shell_sort(arr):
n = len(arr)
gap = n // 2
while gap > 0:
for i in range(gap, n):
j = i
while j >= gap and arr[j-gap] > arr[j]:
arr[j], arr[j-gap] = arr[j-gap], arr[j]
j -= gap
print(arr)
gap //= 2
### 冒泡排序
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]
print(arr)
### 快速排序
def quick_sort(arr):
if len(arr) <= 1:
return arr
else:
pivot = arr[0]
left = [x for x in arr[1:] if x < pivot]
right = [x for x in arr[1:] if x >= pivot]
return quick_sort(left) + [pivot] + quick_sort(right)
### 简单选择排序
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]
print(arr)
### 堆排序
def heap_sort(arr):
def heapify(arr, n, i):
largest = i
l = 2*i + 1
r = 2*i + 2
if l < n and arr[largest] < arr[l]:
largest = l
if r < n and arr[largest] < arr[r]:
largest = r
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)
print(arr)
### 归并排序
def merge_sort(arr):
def merge(arr, l, m, r):
n1 = m - l + 1
n2 = r - m
L = [0] * n1
R = [0] * n2
for i in range(n1):
L[i] = arr[l + i]
for i in range(n2):
R[i] = arr[m + i + 1]
i = j = 0
k = l
while i < n1 and j < n2:
if L[i] <= R[j]:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1
while i < n1:
arr[k] = L[i]
i += 1
k += 1
while j < n2:
arr[k] = R[j]
j += 1
k += 1
def merge_sort_helper(arr, l, r):
if l < r:
m = (l + r) // 2
merge_sort_helper(arr, l, m)
merge_sort_helper(arr, m+1, r)
merge(arr, l, m, r)
merge_sort_helper(arr, 0, len(arr)-1)
print(arr)
# 测试代码
arr = [5, 3, 8, 4, 2, 1, 9, 6, 7]
insert_sort(arr.copy())
shell_sort(arr.copy())
bubble_sort(arr.copy())
print(quick_sort(arr.copy()))
selection_sort(arr.copy())
heap_sort(arr.copy())
merge_sort(arr.copy())
阅读全文