簡體   English   中英

Python - 冒泡排序錯誤索引超出范圍

[英]Python - bubble sort error index out of range

我正在嘗試創建簡單的冒泡排序代碼。 我得到的錯誤是索引超出范圍。 只是想弄清楚我做錯了什么。

我嘗試使用不同的括號並更改 i 變量。

user_array = list()
last = len(user_array)

def swap(a,b) :
    temp = a
    a = b
    b = temp
    return (a,b)

for i in range(0,10):
    word = input ('Enter a number into the array :')
    user_array.append(word)
print (user_array[4])

last = len(user_array)
swapped = True
while swapped == True :
    swapped = False
    i = 0
    while i < last :
        if user_array[i]>user_array[i+1] :
            swap (user_array[i],user_array[i+1])
            swapped = True
        i = i+1
print (user_array)

代碼應按升序對輸入的數字列表進行排序

好的,就這樣。

def bubble_sort( a ) :
    for i in range(len(a)-1) :
        for j in range(i+1, len(a)) :
            if a[i] > a[j] :
                a[i], a[j] = a[j], a[i]  # swap. simple, isn't it?
    return a

print bubble_sort( [6,3,6,23,7,5,8,4e6] )

[3, 5, 6, 6, 7, 8, 23, 4000000.0]

主要外賣:

  1. 創建一個單獨的函數,不要簡單地將所有代碼填充到文件中
  2. 簡單一點
  3. 易於閱讀和理解
  4. 冒泡排序通常是2 for一個在另一個內部循環-是的。
  5. 不要忘記返回值=)

是的,不要使用while循環,它們會永遠運行,並且很難調試或推斷其完成時間。

只是增加一些價值。

數字 = [6, 2, 3]

def 排序(數字):

limit = len(nums)

for i in range(limit):
    for j in range(limit):
        if nums[i] < nums[j]:
            temp = nums[i]
            min = nums[j]
            nums[i] = min
            nums[j] = temp

print(nums)

暫無
暫無

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

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