[英]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]
主要外賣:
for
一個在另一個內部循環-是的。 是的,不要使用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.