python递归排序组合_Python合并递归排序

我的merge_sort函数有问题,特别是对右子列表执行递归排序。在

对此分配给出的提示是:# if min_ < max_

# calculate mid ((min + max) // 2)

#recursively sort left sub-list

# recursively sort right sub-list

# merge sorted sub-lists

# merge_sort function

"""

:param unsorted_list: The list to be sorted

:param min_: The minimum index to sort from the given list

:param max_: The maximum index to sort from the given list

Returns nothing, the original list is modified so no copy is needed

"""

合并排序功能

^{pr2}$

用上面的测试列表测试我的函数可以得到:[1, 2, 4, 12, 20, 17, 3, 11, 18, 1]

这表示左子列表正在工作,但右子列表不工作。在

预期输出应返回的值:[1, 1, 2, 3, 4, 11, 12, 17, 18, 20]

我的合并函数代码:def merge(unsorted_list, min_, max_):

# mid position = start of second sub-list

mid = ((min_ + max_) // 2) + 1

position1 = min_

position2 = mid

position3 = 0

temp = []

stop = False

while stop == False and position2 < len(unsorted_list) and position1 < mid:

if unsorted_list[position1] <= unsorted_list[position2]:

temp.append(unsorted_list[position1])

position1 += 1

position3 += 1

else:

temp.append(unsorted_list[position2])

position2 += 1

position3 += 1

if position1 >= position2:

for k in range(position1, mid + 1):

temp.append(unsorted_list[k])

position2 += 1

position3 += 1

stop = True

if position3 == len(unsorted_list):# temp

for i in range(len(temp)):

unsorted_list[min_] = temp[i]

min_ += 1

elif position2 > max_:

for k in range(position1, mid):

temp.append(unsorted_list[k])

position3 += 1

stop = True

if position3 == len(unsorted_list):# temp

for i in range(len(temp)):

unsorted_list[min_] = temp[i]

min_ += 1

if position3 != len(unsorted_list):

for k in range(position2, len(unsorted_list)):

temp.append(unsorted_list[k])

position3 += 1

if position3 > max_ and position3 == len(temp):

for i in range(len(temp)):

unsorted_list[min_] = temp[i]

min_ += 1

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值