随机十个数,分别使用选择排序、希尔排序、快速排序、归并排序和基数排序使数据集有序
时间: 2023-10-16 12:06:20 浏览: 66
好的,我可以帮你实现这个问题。以下是我编写的Python代码:
```python
import random
# 生成随机数列表
nums = [random.randint(1, 100) for _ in range(10)]
print("原始数据:", nums)
# 选择排序
def selection_sort(nums):
n = len(nums)
for i in range(n-1):
min_idx = i
for j in range(i+1, n):
if nums[j] < nums[min_idx]:
min_idx = j
nums[i], nums[min_idx] = nums[min_idx], nums[i]
selection_sort(nums)
print("选择排序结果:", nums)
# 希尔排序
def shell_sort(nums):
n = len(nums)
gap = n // 2
while gap > 0:
for i in range(gap, n):
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
shell_sort(nums)
print("希尔排序结果:", nums)
# 快速排序
def quick_sort(nums):
if len(nums) <= 1:
return nums
pivot = nums[0]
left, right = [], []
for num in nums[1:]:
if num < pivot:
left.append(num)
else:
right.append(num)
return quick_sort(left) + [pivot] + quick_sort(right)
nums = quick_sort(nums)
print("快速排序结果:", nums)
# 归并排序
def merge_sort(nums):
if len(nums) <= 1:
return nums
mid = len(nums) // 2
left = merge_sort(nums[:mid])
right = merge_sort(nums[mid:])
return merge(left, right)
def merge(left, right):
result = []
i, j = 0, 0
while i < len(left) and j < len(right):
if left[i] < right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
result += left[i:]
result += right[j:]
return result
nums = merge_sort(nums)
print("归并排序结果:", nums)
# 基数排序
def radix_sort(nums):
max_digit = len(str(max(nums)))
for i in range(max_digit):
buckets = [[] for _ in range(10)]
for num in nums:
digit = (num // 10**i) % 10
buckets[digit].append(num)
nums = []
for bucket in buckets:
nums.extend(bucket)
return nums
nums = radix_sort(nums)
print("基数排序结果:", nums)
```
你可以运行这段代码,查看程序输出结果。这里我分别使用了选择排序、希尔排序、快速排序、归并排序和基数排序对数据集进行排序,并将排序结果输出。如果你还有其他问题,可以继续提出。
阅读全文