在python中实现快速排序和交换透视值

时间:2016-10-29 09:49:29

标签: python algorithm python-3.x sorting quicksort

我们知道在实施快速排序时,我们选择一个透视值。在分区阶段,我们用右标记交换透视值。 这是我的代码:

def quicksort(mylist):
    quicksorthelper(mylist,0,len(mylist)-1)


def quicksorthelper(mylist,first,last):
   if first< last:
      splitpoint=partition(mylist,first,last)
      quicksorthelper(mylist,first,splitpoint-1)
      quicksorthelper(mylist,splitpoint+1,last)

def partition(mylist,first,last):
    pivot= mylist[first]
    leftmark= first +1
    rightmark= last
    done = False
    counter = 0
    while not done:
          while leftmark <= rightmark and mylist[leftmark]< pivot:
                leftmark = leftmark +1
          while leftmark <= rightmark and mylist[rightmark]>pivot:
                rightmark= rightmark -1

          if leftmark>rightmark:
            done = True
          else:
              temp = mylist[leftmark]
              mylist[leftmark]=mylist[rightmark]
              mylist[rightmark]=temp
              counter +=1


    temp= pivot                  #pivot = mylist[first]
    pivot = mylist[rightmark]
    mylist[rightmark]=temp

    return rightmark

mylist= [54,26,93,17,77,31,44,55,20]
quicksort(mylist)
print(mylist)

所以问题是如果我写了pivot而不是mylist [first]程序没有工作,而如果我用mindist [first]代替pivot而用rightmark交换值,它就可以了。你能告诉我为什么会这样吗

此外,如果我尝试做类似的事情:    mylist = [54, 26, 93, 17, 77, 31, 44, 55, 20] sortlist=quicksort(mylist) print(sortlist) 那么输出是None。不知道那个

有什么问题

2 个答案:

答案 0 :(得分:2)

此实施不起作用:

temp= pivot                  #pivot = mylist[first]
pivot = mylist[rightmark]
mylist[rightmark]=temp

因为当你

没有变异 mylist
pivot = mylist[rightmark]

您只是为变量pivot分配新值

>>> i = 2
>>> j = 4
>>> somelist = ['a','b','c','d','e','f','g']
>>> pivot = somelist[i]
>>> pivot
'c'
>>> temp = pivot
>>> pivot = somelist[j]
>>> pivot
'e'
>>> somelist[j] = temp
>>> pivot
'e'
>>> somelist
['a', 'b', 'c', 'd', 'c', 'f', 'g']

出于同样的原因,执行以下操作不会更改列表:

>>> anotherlist = [1, 2, 3]
>>> x = anotherlist[1]
>>> x
2
>>> x = 53
>>> x
53
>>> anotherlist
[1, 2, 3]

你必须这样做:

>>> anotherlist[0] = 53
>>> anotherlist
[53, 2, 3]
>>> 

或者你可以使用mutator方法。

最后,您不需要temp变量来在Python中进行交换:

>>> a = 42
>>> b = 88
>>> a,b = b,a
>>> a
88
>>> b
42
>>> 

或列表:

>>> somelist = ['a','b','c','d','e','f','g']
>>> i = 2
>>> j = 4
>>> somelist[i], somelist[j] = somelist[j], somelist[i]
>>> somelist
['a', 'b', 'e', 'd', 'c', 'f', 'g']

答案 1 :(得分:0)

关于你的上一个问题:quicksort不会返回任何内容。这就是为什么sortlist=quicksort(mylist)将排序列表设置为None

阅读How do I pass a variable by reference?以了解最新情况。