没有内置的从最高到最低排序

时间:2017-04-24 07:27:27

标签: python python-3.x

如何在没有内置函数的情况下编写从最高到最低排序的排序函数?

例如:

A=[2,4,6]
sorthightolow(A)
A=[6,4,2]

1 个答案:

答案 0 :(得分:-1)

我不知道为什么没有内置函数就会这样做,但这是一个有效的冒泡排序示例。 http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort#Python

def bubble_sort(seq):
    """Inefficiently sort the mutable sequence (list) in place.
       seq MUST BE A MUTABLE SEQUENCE.

       As with list.sort() and random.shuffle this does NOT return 
    """
    changed = True
    while changed:
        changed = False
        for i in xrange(len(seq) - 1):
            if seq[i] > seq[i+1]:
                seq[i], seq[i+1] = seq[i+1], seq[i]
                changed = True
    return seq

if __name__ == "__main__":
   """Sample usage and simple test suite"""

   from random import shuffle

   testset = range(100)
   testcase = testset[:] # make a copy
   shuffle(testcase)
   assert testcase != testset  # we've shuffled it
   bubble_sort(testcase)
   assert testcase == testset  # we've unshuffled it back into a copy