我试图按降序对列表进行排序,并获得按降序对列表进行排序所需的交换次数[3,1,2]→[3,2,1]。即使用python从列表的最高元素到最低元素。我具有的功能是以[3,1,2]→[1,2,3]的升序对列表进行排序。我将如何以降序对其进行排序,并获得对列表进行排序所需的交换次数?
def count_inversions(ratings):
swap = 0;
for i in range(len(ratings)):
if(i + 1 != ratings[i]):
t = i
while(ratings[t] != i+1):
t++
temp = ratings[t]
ratings[t] = ratings[i]
ratings[i] = temp
swap = swap + 1
return swap
答案 0 :(得分:0)
前段时间我写了一个气泡排序代码,它可能对您有帮助
def bubble_sort(arr, reversed=False):
swap_cnt = 0
i = len(arr) - 1
while i > 0:
for j in range(i):
if not reversed:
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
swap_cnt += 1
if reversed:
if arr[j] < arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
swap_cnt += 1
i -= 1
print('Number of swaps: {}'.format(swap_cnt))
return arr
if __name__ == "__main__":
print(bubble_sort([2, 4, 8, 5, 1, 9, 4]))
print(bubble_sort([2, 4, 8, 5, 1, 9, 4], reversed=True))