排序算法比较代码,要求:用随机数产生100000个待排序元素的关键字值,测试排序函数的机器实际执行时间
时间: 2024-05-13 09:19:46 浏览: 106
以下是使用 Python 实现常见排序算法的比较代码,使用随机数生成100000个待排序元素并输出每个算法的执行时间:
```python
import random
import time
# 生成随机数组
arr = [random.randint(1, 1000) for _ in range(100000)]
# 冒泡排序
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]
start_time = time.time()
bubble_sort(arr)
end_time = time.time()
print("Bubble Sort:", end_time - start_time)
# 选择排序
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]
start_time = time.time()
selection_sort(arr)
end_time = time.time()
print("Selection Sort:", end_time - start_time)
# 插入排序
def insertion_sort(arr):
n = len(arr)
for i in range(1, n):
key = arr[i]
j = i-1
while j >= 0 and key < arr[j]:
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key
start_time = time.time()
insertion_sort(arr)
end_time = time.time()
print("Insertion Sort:", end_time - start_time)
# 快速排序
def quick_sort(arr, low, high):
if low < high:
pi = partition(arr, low, high)
quick_sort(arr, low, pi-1)
quick_sort(arr, pi+1, high)
def partition(arr, low, high):
pivot = arr[high]
i = low-1
for j in range(low, high):
if arr[j] < pivot:
i += 1
arr[i], arr[j] = arr[j], arr[i]
arr[i+1], arr[high] = arr[high], arr[i+1]
return i+1
start_time = time.time()
quick_sort(arr, 0, len(arr)-1)
end_time = time.time()
print("Quick Sort:", end_time - start_time)
# 归并排序
def merge_sort(arr):
if len(arr) > 1:
mid = len(arr) // 2
left_half = arr[:mid]
right_half = arr[mid:]
merge_sort(left_half)
merge_sort(right_half)
i = j = k = 0
while i < len(left_half) and j < len(right_half):
if left_half[i] < right_half[j]:
arr[k] = left_half[i]
i += 1
else:
arr[k] = right_half[j]
j += 1
k += 1
while i < len(left_half):
arr[k] = left_half[i]
i += 1
k += 1
while j < len(right_half):
arr[k] = right_half[j]
j += 1
k += 1
start_time = time.time()
merge_sort(arr)
end_time = time.time()
print("Merge Sort:", end_time - start_time)
```
注意,不同机器的运行时间可能会有所不同。
阅读全文