簡體   English   中英

在我的基本氣泡排序中,我在做什么錯?

[英]What am I doing wrong in my basic bubble sort?

我正在嘗試進行基本的冒泡排序,並計算完成通行證和交換的次數。

因此,對於示例輸入:

23這僅僅是下面的數字量。不要問為什么我不能只使用len()

20 18 8 11 17 12 13 21 10 14 9 5 19 6 16 7 2 15 1 3 22 4 23

def bubbleSort(amount, numbers):
    sorted = False
    swapCount, passCount = 0,0

    while not sorted:
        sorted = True
        for i in range(amount-1):
            if numbers[i] > numbers[i+1]:
                sorted = False
                swapCount += 1
                numbers[i], numbers[i+1] = numbers[i+1], numbers[i]
        passCount += 1
    print(numbers)
    print('%s %s') % (passCount, swapCount)

bubbleSort(input(),raw_input().split())

自然,預期的輸出將是:

19次通過,151次互換,並且列表按正確的順序排列(從小到大)。 但是,我最終得到19個通行證和109個掉期,並且我的訂單看起來像這樣:

['1', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '2', '20', '21', '22', '23', '3', '4', '5', '6', '7', '8', '9']

任何人都可以引導我正確地選擇事物的正確方向,並且2不被認為大於10嗎?

raw_input().split()是一個字符串列表,而不是整數。 您的算法是正確的-您正在按字母順序對字符串進行排序。

一個快速的解決方法是使用例如

bubbleSort(input(), [int(x) for x in raw_input().split()])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM