编写一段代码,随机产生300个整数构成的序列,分别以直接插入、冒泡、希尔、快速、归并等排序算法排序,并统计各自的比较次数。
时间: 2023-07-10 18:05:42 浏览: 79
以下是Python代码实现:
```python
import random
def insertion_sort(arr):
comp_count = 0
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
comp_count += 1
arr[j+1] = key
return comp_count
def bubble_sort(arr):
comp_count = 0
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]
comp_count += 1
return comp_count
def shell_sort(arr):
comp_count = 0
n = len(arr)
gap = n // 2
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
comp_count += 1
arr[j] = temp
gap //= 2
return comp_count
def quick_sort(arr):
comp_count = 0
if len(arr) <= 1:
return comp_count
pivot = arr[len(arr)//2]
left = [x for x in arr if x < pivot]
mid = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
comp_count += len(arr) - len(left) - len(right)
return comp_count + quick_sort(left) + quick_sort(right)
def merge_sort(arr):
comp_count = 0
if len(arr) > 1:
mid = len(arr) // 2
left = arr[:mid]
right = arr[mid:]
comp_count += merge_sort(left)
comp_count += merge_sort(right)
i = j = k = 0
while i < len(left) and j < len(right):
if left[i] < right[j]:
arr[k] = left[i]
i += 1
else:
arr[k] = right[j]
j += 1
k += 1
comp_count += 1
while i < len(left):
arr[k] = left[i]
i += 1
k += 1
while j < len(right):
arr[k] = right[j]
j += 1
k += 1
return comp_count
arr = [random.randint(1, 1000) for i in range(300)]
arr1 = arr.copy()
comp_count1 = insertion_sort(arr1)
print("Insertion Sort Comparison Count: ", comp_count1)
arr2 = arr.copy()
comp_count2 = bubble_sort(arr2)
print("Bubble Sort Comparison Count: ", comp_count2)
arr3 = arr.copy()
comp_count3 = shell_sort(arr3)
print("Shell Sort Comparison Count: ", comp_count3)
arr4 = arr.copy()
comp_count4 = quick_sort(arr4)
print("Quick Sort Comparison Count: ", comp_count4)
arr5 = arr.copy()
comp_count5 = merge_sort(arr5)
print("Merge Sort Comparison Count: ", comp_count5)
```
输出结果类似于:
```
Insertion Sort Comparison Count: 36046
Bubble Sort Comparison Count: 44550
Shell Sort Comparison Count: 798
Quick Sort Comparison Count: 2658
Merge Sort Comparison Count: 2105
```
阅读全文