段合并排序算法(附代码)


前言

学无止境,笔勤不辍。今天更新一道作业题好多人都被困住了,笔者也花了一些时间…后续会附上详细解释
使用的是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)

总结

最近笔者有点忙…更新可能不太及时,希望大家见谅…

  • 13
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值