如何使用冒泡排序来排列列表,但按降序排列? 我搜索了其他主题,但找不到答案。 这是我的冒泡排序代码的工作实现:
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()
您需要将以下 if 语句中的大于
if alist[i]<alist[i+1]:
替换为小于if alist[i]<alist[i+1]:
。您还需要返回 alist,留下以下内容。
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[i]<alist[i+1]
反向冒泡排序的两种可能的解决方案。
解决方案1:这里j从右向左移动
>x = [2,80,99,2,34,57,7,68,9,0,77,19,24]
# i travels from len(x)-1= lst index, 0, -1 steps to be taken
for i in range(len(x)-1,0,-1):
# here j travels from 0th index to ith index
for j in range(i):
if x[j]<x[j+1]:
x[j+1],x[j] = x[j],x[j+1]
print(x)
解决方案2:这里j从左向右移动
> arr = [2,80,99,2,34,57,7,68,9,0,77,19,24]
#start i from last index + 1 in arr, and step down by 1 till 0th index acting as round counter.
for i in range(len(arr),0,-1):
#start inner loop j that can traverse from last index till length(arr)-i ....
# .... with 1 step down every time to limit j from going beyond length(arr)-i towards left of arr.
for j in range(len(arr)-1,len(arr)-i,-1):
#check if the left adjacent element is less than current element at j.
if arr[j-1]<arr[j]:
#if above condition is true, swap the adjacent element and element at j.
arr[j], arr[j-1] = arr[j-1], arr[j]
print(arr)