请用一段代码完成直接插入、冒泡、直接选择、快速、堆、归并等排序算法,并根据运行时间比较各种排序算法的运行速度。采用随机数发生器产生待排序整型数据,值的范围在0到n*10之间,排序长度默认20000,编写各种排序程序记录运行速度并做对比分析。
时间: 2024-02-04 16:04:25 浏览: 75
好的,以下是使用 Python 实现的六种排序算法和运行时间比较的代码:
```python
import time
import random
# 直接插入排序
def insert_sort(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and arr[j] > key:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
# 冒泡排序
def bubble_sort(arr):
for i in range(len(arr) - 1):
for j in range(len(arr) - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
# 直接选择排序
def select_sort(arr):
for i in range(len(arr)):
min_index = i
for j in range(i + 1, len(arr)):
if arr[j] < arr[min_index]:
min_index = j
arr[i], arr[min_index] = arr[min_index], arr[i]
# 快速排序
def quick_sort(arr, left, right):
if left >= right:
return
pivot = arr[left]
i, j = left, right
while i < j:
while i < j and arr[j] >= pivot:
j -= 1
arr[i] = arr[j]
while i < j and arr[i] <= pivot:
i += 1
arr[j] = arr[i]
arr[i] = pivot
quick_sort(arr, left, i - 1)
quick_sort(arr, i + 1, right)
# 堆排序
def heap_sort(arr):
def heapify(arr, n, i):
largest = i
l, r = i * 2 + 1, i * 2 + 2
if l < n and arr[l] > arr[largest]:
largest = l
if r < n and arr[r] > arr[largest]:
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)
# 归并排序
def merge_sort(arr):
def merge(arr, left, mid, right):
left_arr = arr[left:mid]
right_arr = arr[mid:right]
i, j, k = 0, 0, left
while i < len(left_arr) and j < len(right_arr):
if left_arr[i] < right_arr[j]:
arr[k] = left_arr[i]
i += 1
else:
arr[k] = right_arr[j]
j += 1
k += 1
while i < len(left_arr):
arr[k] = left_arr[i]
i += 1
k += 1
while j < len(right_arr):
arr[k] = right_arr[j]
j += 1
k += 1
def divide(arr, left, right):
if left + 1 < right:
mid = (left + right) // 2
divide(arr, left, mid)
divide(arr, mid, right)
merge(arr, left, mid, right)
divide(arr, 0, len(arr))
# 测试函数
def test_sort(sort_func, arr):
start_time = time.time()
sort_func(arr)
end_time = time.time()
return end_time - start_time
# 生成随机数组
n = 20000
arr = [random.randint(0, n * 10) for i in range(n)]
# 测试排序算法
insert_sort_time = test_sort(insert_sort, arr.copy())
bubble_sort_time = test_sort(bubble_sort, arr.copy())
select_sort_time = test_sort(select_sort, arr.copy())
quick_sort_time = test_sort(lambda arr: quick_sort(arr, 0, len(arr) - 1), arr.copy())
heap_sort_time = test_sort(heap_sort, arr.copy())
merge_sort_time = test_sort(merge_sort, arr.copy())
# 输出运行时间
print("Insert sort time: ", insert_sort_time)
print("Bubble sort time: ", bubble_sort_time)
print("Select sort time: ", select_sort_time)
print("Quick sort time: ", quick_sort_time)
print("Heap sort time: ", heap_sort_time)
print("Merge sort time: ", merge_sort_time)
```
运行结果可能会有所不同,但是一般来说,排序算法的运行时间从短到长的顺序是:插入排序、选择排序、冒泡排序、归并排序、快速排序、堆排序。
阅读全文