在左分区没有额外条件的情况下,quicksort python实现失败

时间:2016-12-15 00:08:09

标签: python quicksort

我试着在python中编写一个quicksort的实现(这里有很多可用的,但我的目标是在没有复制/粘贴的情况下尝试自己,只是练习从伪代码到真实代码)

Hello

对于左侧分区,我必须添加条件test = [21, 4, 1, 3, 9, 20, 25, 6, 21, 14] def partition(arr, istart, pivot): while pivot > istart : if arr[pivot] <= arr[istart]: arr[istart], arr[pivot - 1], arr[pivot] = arr[pivot - 1], arr[pivot], arr[istart] pivot -= 1 else: istart += 1 if (pivot + 1 < len(arr) - 1): # right partition partition(arr, pivot + 1, len(arr) - 1 ) if (pivot - 1 > 0) and (pivot < len(arr) - 1) : #left partition partition(arr, 0, pivot -1) return arr def quicksort(arr): if len(arr) < 2: return arr else: return partition(arr, 0, len(arr) - 1) 才能使代码生效,否则我会收到以下错误:(pivot < len(arr) - 1)。 我无法理解为什么我需要额外的条件:左侧分区的枢轴应该随着左侧越来越多的元素被排序而减少。那么,为什么我需要那个条件呢?

0 个答案:

没有答案
相关问题