Python单参数递归快速排序函数创建问题求助
修复你的单参数递归快速排序函数
你的代码核心问题有两个:
- 递归时操作的是列表切片的副本,副本的排序结果不会同步回原列表,导致原列表始终没被修改
- 右子列表的切片范围错误,漏掉了最后一个元素
下面是基于你原有代码结构的修复版本,尽量保留了你的分区逻辑:
def quicksort(copyLyst): low = 0 # 简化写法,等价于len(copyLyst)-len(copyLyst) high = len(copyLyst) - 1 # Base Case:长度<=1直接返回原列表 if high <= low: return copyLyst center = low + (high - low) // 2 pivot = copyLyst[center] first = low last = high # Partitioning 分区逻辑完全保留你的写法 done = False while not done: while copyLyst[first] < pivot: first = first + 1 while pivot < copyLyst[last]: last = last - 1 if first >= last: done = True else: swap = copyLyst[first] copyLyst[first] = copyLyst[last] copyLyst[last] = swap first = first + 1 last = last - 1 # 递归排序左右子列表,注意修正右子列表的切片范围 leftCopy = copyLyst[low:last + 1] sorted_left = quicksort(leftCopy) # 将排序后的左子列表替换回原列表对应位置 copyLyst[low:last + 1] = sorted_left rightCopy = copyLyst[last + 1:high + 1] # 这里改成high+1,确保包含最后一个元素 sorted_right = quicksort(rightCopy) # 将排序后的右子列表替换回原列表对应位置 copyLyst[last + 1:high + 1] = sorted_right return copyLyst
关键修改点说明
- Base Case返回原列表:让递归调用能拿到排序后的子列表,方便后续替换回原列表
- 替换排序后的子列表:因为切片是创建新列表,递归排序的是副本,所以要把排序好的副本赋值回原列表的对应区间,才能让原列表逐步有序
- 修正右子列表切片范围:原代码
copyLyst[last + 1:high]是左闭右开区间,会漏掉索引为high的元素,改成high+1才能包含最后一个元素
测试示例:
test_list = [3,1,4,1,5,9,2,6] print(quicksort(test_list)) # 输出: [1, 1, 2, 3, 4, 5, 6, 9]
内容的提问来源于stack exchange,提问作者burningyeti
相关产品推荐
相关产品推荐

