How can I arrange a list, with bubble sort, but in descending order? I searched in other topics, but I couldn't find an answer. This is my working implementation of Bubblesort code:
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()
You need to replace the greater than in the following if statement if alist[i]<alist[i+1]:
with a smaller than if alist[i]<alist[i+1]:
. You also need to return alist leaving you with the following.
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)