1.随机产生500个1~-2000 之问的整数并输出,完成以下操作: (1)对给定整数进行直接插入排序,显示排序所用时间; (2)对给定整数进行希尔排序,显示排序所用时间; 3)对给定整数进行老泡排序,显示排序所用时间; (4)对给定整数进行快速排序,显示排序所用时间。
时间: 2024-03-14 08:48:13 浏览: 90
以下是 Python 代码实现:
```python
import random
import time
# 生成随机整数列表
nums = [random.randint(1, -2000) for _ in range(500)]
# 直接插入排序
def insertion_sort(nums):
start_time = time.time()
for i in range(1, len(nums)):
key = nums[i]
j = i - 1
while j >= 0 and nums[j] > key:
nums[j + 1] = nums[j]
j -= 1
nums[j + 1] = key
end_time = time.time()
return nums, end_time - start_time
# 希尔排序
def shell_sort(nums):
start_time = time.time()
gap = len(nums) // 2
while gap > 0:
for i in range(gap, len(nums)):
temp = nums[i]
j = i
while j >= gap and nums[j - gap] > temp:
nums[j] = nums[j - gap]
j -= gap
nums[j] = temp
gap //= 2
end_time = time.time()
return nums, end_time - start_time
# 老泡排序
def bubble_sort(nums):
start_time = time.time()
for i in range(len(nums) - 1):
for j in range(len(nums) - i - 1):
if nums[j] > nums[j + 1]:
nums[j], nums[j + 1] = nums[j + 1], nums[j]
end_time = time.time()
return nums, end_time - start_time
# 快速排序
def quick_sort(nums):
if len(nums) <= 1:
return nums
pivot = nums[0]
left = [x for x in nums[1:] if x < pivot]
right = [x for x in nums[1:] if x >= pivot]
return quick_sort(left) + [pivot] + quick_sort(right)
# 测试排序算法的效率
print("原始列表:", nums)
print("直接插入排序:", insertion_sort(nums.copy())[1])
print("希尔排序:", shell_sort(nums.copy())[1])
print("老泡排序:", bubble_sort(nums.copy())[1])
start_time = time.time()
quick_sort(nums.copy())
print("快速排序:", time.time() - start_time)
```
代码中的 `random` 模块用于生成随机整数列表,`time` 模块用于计算排序算法所用时间。四个排序算法分别为直接插入排序、希尔排序、老泡排序和快速排序。最后通过调用函数并输出其返回值来测试排序算法的效率。
阅读全文