我这里有一个快速排序程序,但结果似乎有问题。我认为在引用某些值时,下面突出显示的区域肯定存在一些问题。有什么建议吗?
#where l represents low, h represents high
def quick(arr,l,h):
#is this the correct array for quicksorting?
if len(x[l:h]) > 1:
#r is pivot POSITION
r = h
#R is pivot ELEMENT
R = arr[r]
i = l-1
for a in range(l,r+1):
if arr[a] <= arr[r]:
i+=1
arr[i], arr[a] = arr[a], arr[i]
#should I take these values? Note that I have repeated elements below, which is what I want to deal with
quick(arr,l,arr.index(R)-1)
quick(arr,arr.index(R)+arr.count(R),h)
x = [6,4,2,1,7,8,5,3]
quick(x,0,len(x)-1)
print(x)
答案 0 :(得分:1)
#should I take these values? Note that I have repeated elements below, which is what I want to deal with quick(arr,l,arr.index(R)-1) quick(arr,arr.index(R)+arr.count(R),h)
您似乎假设等于pivot元素的值已经连续。对于当前的实现,这种假设可能是错误的。测试它,例如通过在递归之前输出完整列表。
为了使假设成立,分为三组而不是两组,如at Wikipedia所述。
答案 1 :(得分:1)
请检查一下。我想你找到答案了。
def partition(array, begin, end):
pivot = begin
for i in xrange(begin+1, end+1):
if array[i] <= array[begin]:
pivot += 1
array[i], array[pivot] = array[pivot], array[i]
array[pivot], array[begin] = array[begin], array[pivot]
return pivot
def quicksort(array, begin=0, end=None):
if end is None:
end = len(array) - 1
if begin >= end:
return
pivot = partition(array, begin, end)
quicksort(array, begin, pivot-1)
quicksort(array, pivot+1, end)
array = [6,4,2,1,7,8,5,3]
quicksort(array)
print (array)