快速排序的元组与python

时间:2015-02-13 16:17:55

标签: algorithm python-2.7 sorting quicksort

我试图在其操作算法quicksort中执行此操作,以排序元组列表的元素。或者如果我有这种类型的列表[(0,1),(1,1),(2,1),(3,3),(4,2),(5,1),(6,4) )]我想在每个元组的第二个元素的函数中对它进行排序并获得[(6,4),(3,3),(4,2),(0,1),(1,1),( 2,1),(5,1)]。我尝试过使用以下算法:

def partition(array, begin, end, cmp):
pivot=array[end][1]
ii=begin
for jj in xrange(begin, end):
  if cmp(array[jj][1], pivot):
    array[ii], array[jj] = array[jj], array[ii]
    ii+=1
array[ii], array[end] = pivot, array[ii]
return ii

enter code hedef sort(array, cmp=lambda x, y: x > y, begin=0, end=None):
if end is None: end = len(array)
if begin < end:
    i = partition(array, begin, end-1, cmp)
    sort(array, cmp, i+1, end)
    sort(array, cmp, begin, i)

问题是结果如下:[4,(3,3),(4,2),1,1,1,(5,1)]。我需要改变什么来获得正确的结果?

2 个答案:

答案 0 :(得分:0)

Python中的复杂排序模式是无痛的。 Python sorting algorithm是最先进的,是现实案例中速度最快的之一。无需算法设计。

>>> from operator import itemgetter
>>> l = [(0,1), (1,1), (2,1), (3,3), (4,2), (5,1), (6,4 )]
>>> l.sort(key=itemgetter(1), reverse=True)
>>> l
[(6, 4), (3, 3), (4, 2), (0, 1), (1, 1), (2, 1), (5, 1)]

在上面,itemgetter返回一个返回其参数的第二个元素的函数。因此,key的{​​{1}}参数是一个函数,它返回对列表进行排序的项目。

Python的排序是稳定的,因此具有相等键的元素的排序(在这种情况下,每个元组的第二项)由原始顺序决定。

答案 1 :(得分:0)

不幸的是,@ wkschwartz的回答只能起作用,因为条款的特殊开始排序。如果将元组(5,1)移动到列表的开头,则它会给出不同的答案。

以下(第一个)方法的作用是,它为初始列表中项目的任何初始排序提供相同的结果。

Python 3.4.2 |Continuum Analytics, Inc.| (default, Oct 22 2014, 11:51:45) [MSC v
.1600 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.

>>> l = [(0,1), (1,1), (2,1), (3,3), (4,2), (5,1), (6,4 )]
>>> sorted(l, key=lambda x: (-x[1], x[0]))
[(6, 4), (3, 3), (4, 2), (0, 1), (1, 1), (2, 1), (5, 1)]
>>> from operator import itemgetter
>>> sorted(l, key=itemgetter(1), reverse=True)
[(6, 4), (3, 3), (4, 2), (0, 1), (1, 1), (2, 1), (5, 1)]
>>> # but note:
>>> l2 = [(5,1), (1,1), (2,1), (3,3), (4,2), (0,1), (6,4 )]
>>> # Swapped first and sixth elements
>>> sorted(l2, key=itemgetter(1), reverse=True)
[(6, 4), (3, 3), (4, 2), (5, 1), (1, 1), (2, 1), (0, 1)]
>>> sorted(l2, key=lambda x: (-x[1], x[0]))
[(6, 4), (3, 3), (4, 2), (0, 1), (1, 1), (2, 1), (5, 1)]
>>>