问题描述
好吧,所以我试图自己解决三向分区问题,而且我似乎无法理解自己的代码。
我自己做了一个partition3,它将列表分为三个部分:
- 所有项目均小于枢轴值的第一部分
- 所有值均等于枢轴值的第二部分
- 所有值均超出枢轴值的第三部分
此后,partition3函数将返回值m1 m2和分区本身。第一部分(1)和第二部分(2)上的两个递归调用将列表进一步划分,就像在任何标准化的分治法中一样。
我已经了解其他解决方案,只是我不明白为什么我自己的解决方案会失败
# Uses python3
import sys
import random
def partition3(a,l,r):
x = a[l]
j = l
count = 0
for i in range(l + 1,r + 1):
if a[i] == x:
count = count + 1
a = [a[i]] + a
a.pop(i+1)
j += 1
elif a[i] < x:
j += 1
a[i],a[j] = a[j],a[i]
final_partition = a[count+1:j+1] + a[:count+1] + a[j+1:]
m1 = j-count
m2 = j
return m1,m2,final_partition
# def partition2(a,r):
# x = a[l]
# j = l
# for i in range(l + 1,r + 1):
# if a[i] <= x:
# j += 1
# a[i],a[i]
# a[l],a[l]
# return j
def randomized_quick_sort(a,r):
if l >= r:
return
k = random.randint(l,r)
a[l],a[k] = a[k],a[l]
m1,b = partition3(a,r)
print(m1,a)
randomized_quick_sort(a,m1 - 1);
randomized_quick_sort(a,m2 + 1,r);
if __name__ == '__main__':
input = sys.stdin.read()
n,*a = list(map(int,input.split()))
randomized_quick_sort(a,n - 1)
for x in a:
print(x,end=' ')
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)