我知道我可以使用sort()函数,但我试图不使用它。
from random import randint
# Create variables
numberArray = [0]*20
# Populate array
for i in range(0,20):
numberArray[i] = randint(0,300)
# Sort array into ascending order
print("Sorting array into ascending order...")
sortedAscending = False
while sortedAscending == False:
for i in range(0,20):
sortedAscending = True
if i != (len(numberArray)-1):
if numberArray[i] > numberArray[i+1]:
temp = numberArray[i]
numberArray[i] = numberArray[i+1]
numberArray[i+1] = temp
sortedAscending = False
for j in range(0,20):
print(numberArray[j])
print("END OF ARRAY")
print()
for i in range(0,20):
print(numberArray[i])
它开始对数组进行排序,但是在几个循环之后无法对任何数字进行排序。请帮忙。 注意:带有“END OF ARRAY”的循环用于调试。
答案 0 :(得分:1)
尝试这个并让我知道它是否有效:)(到目前为止,我已经测试了2-3次它一直运行良好)
from random import randint
# Create variables
numberArray = [0]*20
# Populate array
for i in range(0,20):
numberArray[i] = randint(0,300)
# Sort array into ascending order
print("Sorting array into ascending order...")
sortedAscending = False
while sortedAscending == False:
sortedAscending = True # this should be before the for loop
for i in range(0,20):
if i != (len(numberArray)-1):
if numberArray[i] > numberArray[i+1]:
temp = numberArray[i]
numberArray[i] = numberArray[i+1]
numberArray[i+1] = temp
sortedAscending = False
for j in range(0,20):
print(numberArray[j])
print("END OF ARRAY")
print()
for i in range(0,20):
print(numberArray[i])
我将sortedAscending = True
移出了for循环
答案 1 :(得分:0)
您已实施冒泡排序。
在python交换中,值非常简单。假设你要交换numberArray [i]和numberArray [i + 1]的值 只需你可以使用它。
numberArray[i], numberArray[i+1] = numberArray[i+1], numberArray[i]
这是你的代码。这段代码应该可以正常使用。
from random import randint
# Create variables
numberArray = [0]*20
# Populate array
for i in range(0,20):
numberArray[i] = randint(0,300)
# Sort array into ascending order
print("Sorting array into ascending order...")
sortedAscending = False
while sortedAscending == False:
sortedAscending = True # this should be before the for loop
for i in range(0,20):
if i != (len(numberArray)-1):
if numberArray[i] > numberArray[i+1]:
numberArray[i], numberArray[i+1] = numberArray[i+1], numberArray[i]
sortedAscending = False
for i in range(0,20):
print(numberArray[i])