随机产生300个整数构成的序列,分别以直接插入、冒泡、希尔、快速、归并等排序算法排序,并统计各自的比较次数。代码怎么写
时间: 2023-07-10 19:05:44 浏览: 74
插入排序 冒泡法排序 快速排序 直接选择排序 堆排序 归并排序 希尔排序 7种排序算法及时间比较
5星 · 资源好评率100%
以下是使用Python实现各个排序算法的代码,同时统计比较次数:
```python
import random
# 生成随机数序列
random_list = [random.randint(1, 1000) for i in range(300)]
# 直接插入排序
def insertion_sort(arr):
n = len(arr)
count = 0
for i in range(1, n):
j = i - 1
temp = arr[i]
while j >= 0 and arr[j] > temp:
arr[j+1] = arr[j]
j -= 1
count += 1
arr[j+1] = temp
return arr, count
# 冒泡排序
def bubble_sort(arr):
n = len(arr)
count = 0
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]
count += 1
return arr, count
# 希尔排序
def shell_sort(arr):
n = len(arr)
gap = n // 2
count = 0
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
count += 1
arr[j] = temp
gap //= 2
return arr, count
# 快速排序
def quick_sort(arr, left, right):
if left >= right:
return arr, 0
pivot = arr[left]
i, j = left, right
count = 0
while i < j:
while i < j and arr[j] >= pivot:
j -= 1
count += 1
if i < j:
arr[i] = arr[j]
i += 1
while i < j and arr[i] < pivot:
i += 1
count += 1
if i < j:
arr[j] = arr[i]
j -= 1
arr[i] = pivot
_, count1 = quick_sort(arr, left, i-1)
_, count2 = quick_sort(arr, i+1, right)
count += count1 + count2
return arr, count
# 归并排序
def merge_sort(arr):
if len(arr) <= 1:
return arr, 0
mid = len(arr) // 2
left, count1 = merge_sort(arr[:mid])
right, count2 = merge_sort(arr[mid:])
count = count1 + count2
i, j = 0, 0
merge_list = []
while i < len(left) and j < len(right):
if left[i] <= right[j]:
merge_list.append(left[i])
i += 1
else:
merge_list.append(right[j])
j += 1
count += 1
merge_list += left[i:]
merge_list += right[j:]
return merge_list, count
# 统计各个排序算法的比较次数
_, count_insertion = insertion_sort(random_list.copy())
_, count_bubble = bubble_sort(random_list.copy())
_, count_shell = shell_sort(random_list.copy())
_, count_quick = quick_sort(random_list.copy(), 0, len(random_list)-1)
_, count_merge = merge_sort(random_list.copy())
# 输出结果
print("随机数序列:", random_list)
print("直接插入排序比较次数:", count_insertion)
print("冒泡排序比较次数:", count_bubble)
print("希尔排序比较次数:", count_shell)
print("快速排序比较次数:", count_quick)
print("归并排序比较次数:", count_merge)
```
这里使用Python内置的`random`库生成300个随机整数构成的序列,然后分别使用直接插入排序、冒泡排序、希尔排序、快速排序和归并排序来对这个序列进行排序,并统计各自的比较次数。
阅读全文