前言
学无止境,笔勤不辍。今天更新一道作业题好多人都被困住了,笔者也花了一些时间…后续会附上详细解释
使用的是python
一、题目
段合并排序算法:
将数组划分为n1/2个子数组,每个子数组有n1/2个元素。然后递归地对分割后的子数组进行排序,最后将所得到的个排好序的子数组合并排序。
二、代码
import math
def n_sort_function(nums, start, end):
if end - start == 1 and end != len(nums) - 1:
return nums
if end == len(nums) - 1 and start == end - 1:
if nums[start] > nums[end]:
nums[end], nums[start] = nums[start], nums[end]
return nums
flag = nums[start]
nums.pop(start)
i = start - 1
j = start
end = end - 1
while j < end:
if nums[j] < flag:
i += 1
nums[j], nums[i] = nums[i], nums[j]
j += 1
nums.insert(i + 1, flag)
end = end + 1
n_divided = int(math.sqrt(end - start))
while start < end:
if start+n_divided+1>end:
n_sort_function(nums, start, end)
else:
n_sort_function(nums, start, start + n_divided)
start += n_divided+1
if __name__ == "__main__":
nums = [113,22,2,2,2,4,7,11,8,6]
s = 0
length_end = len(nums)
# 以下代码用于合并操作
times =int(math.sqrt(length_end))
all_times = times+int(math.sqrt(length_end-times*times))
for i in range(all_times):
n_sort_function(nums, s+i, length_end)
n_sort_function(nums, s , length_end)
print(nums)
总结
最近笔者有点忙…更新可能不太及时,希望大家见谅…