为什么我的快速排序代码不起作用?

时间:2017-12-25 17:26:16

标签: python sorting recursion

即使我得到正确的分区但输出不正确。似乎它无法重新收集其递归输出。

def Quick_Sort(alist):
  if len(alist)>0:
    print(alist)  
    pivot=alist[-1]
    pivotindex=0
    for i in range(len(alist)-1):
        if alist[i]<pivot:

            alist[i],alist[pivotindex]=alist[pivotindex], alist[i]
            pivotindex +=1
    alist[pivotindex],alist[-1] = alist[-1], alist[pivotindex]
    print(alist) 
    Quick_Sort(alist[:pivotindex])
    Quick_Sort(alist[pivotindex+1:])

alist =input('enter list:')
alist=list(map(int,alist.split()))

Quick_Sort(alist)
print(alist)

输出.............................................. ...............

enter list:4 2 5 3 6 9 1
[4, 2, 5, 3, 6, 9, 1]
[1, 2, 5, 3, 6, 9, 4]
[2, 5, 3, 6, 9, 4]
[2, 3, 4, 6, 9, 5]
[2, 3]
[2, 3]
[2]
[2]
[6, 9, 5]
[5, 9, 6]
[9, 6]
[6, 9]
[9]
[9]
[1, 2, 5, 3, 6, 9, 4]

1 个答案:

答案 0 :(得分:0)

试试这段代码:

def Quick_Sort(alist):
  if len(alist)>0:
    print(alist)  
    pivot=alist[-1]
    pivotindex=0
    for i in range(len(alist)-1):
        if alist[i]<pivot:

            alist[i],alist[pivotindex]=alist[pivotindex], alist[i]
            pivotindex +=1
    alist[pivotindex],alist[-1] = alist[-1], alist[pivotindex]
    print(alist) 
    alist = Quick_Sort(alist[:pivotindex])
    alist = Quick_Sort(alist[pivotindex+1:])
  return alist

alist =input('enter list:')
alist=list(map(int,alist.split()))

Quick_Sort(alist)
print(alist)