Python中的冒泡排序降序列表

时间:2017-05-13 16:33:50

标签: python sorting bubble-sort

如何按冒号排列列表,但按降序排列? 我搜索了其他主题,但我找不到答案。 这是我对Bubblesort代码的工作实现:

from timeit import default_timer as timer
import resource
start = timer()
def bubbleSort(alist):
    for passnum in range(len(alist)-1,0,-1):
        for i in range(passnum):
            if alist[i]>alist[i+1]:
                temp = alist[i]
                alist[i] = alist[i+1]
                alist[i+1] = temp


with open('lista.txt', 'r') as f:
    long_string = f.readline()
    alist = long_string.split(',')
bubbleSort(alist)
f = open("bubble.txt", "w")
print >>f,(alist)
print resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1000
end = timer()
print(end - start)
f.close()

2 个答案:

答案 0 :(得分:0)

像这样写alist[i]<alist[i+1]

答案 1 :(得分:0)

您需要将以下if语句if alist[i]<alist[i+1]:中的大于if alist[i]<alist[i+1]:替换为小于def bubbleSort(alist): for passnum in range(len(alist)-1,0,-1): for i in range(passnum): if alist[i]<alist[i+1]: temp = alist[i] alist[i] = alist[i+1] alist[i+1] = temp return(alist) 。您还需要退回alist,并留下以下内容。

{  
   "a":"aaaa",
   "b":"bbbb",
   "c":{  
      "c1":"c11",
      "c2":"c22"
   },
   "d":[  
      "d1",
      "d2",
      "d3"
   ]
}