Python编写快速排序算法运行后无法得到正确输出问题求助
快速排序代码问题修正
你的代码存在以下几处错误:
- 函数缩进错误:
quickSort函数目前被缩进在partition函数内部,属于局部函数,全局作用域无法调用,需要将quickSort的缩进调整到和partition同级。 - 分区函数边界异常:内层遍历的
while循环没有加索引边界限制,当基准值为当前区间最大值时,i会持续递增超出数组下标范围,触发索引越界。同时外层循环结束时天然满足j <= i,额外的if i > j判断属于多余逻辑,可直接删除。 - 排序调用参数错误:
quickSort的后两个入参是数组待排序区间的左右索引下标,不是数组的首尾元素值,你当前调用时传入的a[0]和a[l-1]是元素值,应修改为0和len(a)-1。
修正后完整代码
def partition(arr, low, high): pivot = arr[low] i = low j = high while i < j: # 新增索引边界判断防止越界 while i <= high and arr[i] <= pivot: i = i + 1 while j >= low and arr[j] > pivot: j = j - 1 if i < j: arr[i], arr[j] = arr[j], arr[i] # 交换基准值到排序后的正确位置 arr[j], arr[low] = arr[low], arr[j] return j # 调整缩进为全局函数 def quickSort(arr, low, high): if low < high: pivot = partition(arr, low, high) quickSort(arr, low, pivot-1) quickSort(arr, pivot+1, high) a = [] n = int(input("Enter the number of elements : ")) print("Enter the elements now") for i in range(0, n): element = int(input()) a.append(element) print("Given array :", a) l = len(a) # 传入正确的索引参数 quickSort(a, 0, l-1) print("Sorted array is :", a)
内容的提问来源于stack exchange,提问作者Mayur Panchal
相关产品推荐
相关产品推荐

