随机产生300个整数构成的序列,分别以直接插入、冒泡、希尔、快速、归并等排序算法排序,并统计各自的比较次数。编写一个源代码
时间: 2023-07-10 19:13:26 浏览: 97
以下是一个基于Python的示例代码,实现了随机产生300个整数序列,以及使用直接插入、冒泡、希尔、快速、归并等排序算法进行排序,并统计比较次数的功能:
```python
import random
# 生成随机整数序列
nums = [random.randint(1, 1000) for _ in range(300)]
# 直接插入排序
def insertion_sort(nums):
n = len(nums)
count = 0
for i in range(1, n):
j = i
while j > 0 and nums[j] < nums[j-1]:
nums[j], nums[j-1] = nums[j-1], nums[j]
j -= 1
count += 1
return count
insertion_count = insertion_sort(nums[:])
# 冒泡排序
def bubble_sort(nums):
n = len(nums)
count = 0
for i in range(n):
for j in range(n-i-1):
if nums[j] > nums[j+1]:
nums[j], nums[j+1] = nums[j+1], nums[j]
count += 1
return count
bubble_count = bubble_sort(nums[:])
# 希尔排序
def shell_sort(nums):
n = len(nums)
count = 0
gap = n // 2
while gap > 0:
for i in range(gap, n):
j = i
while j >= gap and nums[j-gap] > nums[j]:
nums[j], nums[j-gap] = nums[j-gap], nums[j]
j -= gap
count += 1
gap //= 2
return count
shell_count = shell_sort(nums[:])
# 快速排序
def quick_sort(nums):
n = len(nums)
count = 0
if n <= 1:
return count
pivot = nums[0]
left = [x for x in nums[1:] if x < pivot]
right = [x for x in nums[1:] if x >= pivot]
count += len(left) + len(right)
return count + quick_sort(left) + quick_sort(right)
quick_count = quick_sort(nums[:])
# 归并排序
def merge_sort(nums):
n = len(nums)
if n <= 1:
return 0
count = 0
mid = n // 2
left = nums[:mid]
right = nums[mid:]
count += merge_sort(left) + merge_sort(right)
i = j = 0
while i < len(left) and j < len(right):
if left[i] < right[j]:
nums[i+j] = left[i]
i += 1
else:
nums[i+j] = right[j]
j += 1
count += 1
nums[i+j:] = left[i:] + right[j:]
return count
merge_count = merge_sort(nums[:])
# 输出比较次数
print("直接插入排序比较次数:", insertion_count)
print("冒泡排序比较次数:", bubble_count)
print("希尔排序比较次数:", shell_count)
print("快速排序比较次数:", quick_count)
print("归并排序比较次数:", merge_count)
```
以上代码中,使用了Python内置的random模块生成了一个由300个随机整数构成的序列。然后分别定义了直接插入、冒泡、希尔、快速、归并等排序算法,并在每个算法中通过计数器统计比较次数。最后输出了每个算法的比较次数。
阅读全文