随机产生500个1~2000之间的整数并输出,完成以下操作: (1)对给定整数进行直接插入排序,显示排序所用时间; (2)对给定整数进行希尔排序,显示排序所用时间; (3)对给定整数进行起泡排序,显示排序所用时间; (4)对给定整数进行快速排序,显示排序所用时间。
时间: 2023-12-20 20:07:04 浏览: 68
随机产生若干个数,并插入排序
以下是 Python 代码实现:
```python
import random
import time
# 直接插入排序
def insertion_sort(arr):
start_time = time.time()
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
end_time = time.time()
return end_time - start_time
# 希尔排序
def shell_sort(arr):
start_time = time.time()
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
arr[j] = temp
gap //= 2
end_time = time.time()
return end_time - start_time
# 起泡排序
def bubble_sort(arr):
start_time = time.time()
n = len(arr)
for i in range(n):
for j in range(0, n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
end_time = time.time()
return end_time - start_time
# 快速排序
def quick_sort(arr):
start_time = time.time()
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
def quicksort(arr, low, high):
if low < high:
pi = partition(arr, low, high)
quicksort(arr, low, pi - 1)
quicksort(arr, pi + 1, high)
quicksort(arr, 0, len(arr) - 1)
end_time = time.time()
return end_time - start_time
# 随机生成500个1~2000之间的整数
arr = [random.randint(1, 2000) for i in range(500)]
# 对500个整数进行四种排序算法并输出所用时间
print("直接插入排序所用时间:", insertion_sort(arr))
print("希尔排序所用时间:", shell_sort(arr))
print("起泡排序所用时间:", bubble_sort(arr))
print("快速排序所用时间:", quick_sort(arr))
```
输出结果类似于:
```
直接插入排序所用时间: 0.016163110733032227
希尔排序所用时间: 0.0001544952392578125
起泡排序所用时间: 0.023244857788085938
快速排序所用时间: 0.00010848045349121094
```
阅读全文