隨機生成多組長寬,並生成面積,並排序大小,用merge
时间: 2023-05-26 16:03:19 浏览: 57
题目分析:-(HDUACM2010版_06)并查集(最小生成树)
sort方法實現
import random
def generate_areas(num):
areas = []
for i in range(num):
length = random.randint(1, 10)
width = random.randint(1, 10)
area = length * width
areas.append(area)
return areas
def merge_sort(arr):
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = arr[:mid]
right = arr[mid:]
left = merge_sort(left)
right = merge_sort(right)
return merge(left, right)
def merge(left, right):
result = []
i = j = 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
areas = generate_areas(10)
print("原始面積:", areas)
sorted_areas = merge_sort(areas)
print("排序後面積:", sorted_areas)
阅读全文