【发布时间】:2019-08-03 03:17:50
【问题描述】:
我有这个列表,我想根据冒泡排序进行排序,代码中有一个函数 (Swap()) 拒绝工作。我不知道为什么。有代码
score = [92,95,7,5,85,55,789,47,125,3265,88,965,655,3,15,448,0,255,455]
size = len(score)
x = 0
COMPS = size - 1
def swap():
temp = score[x + 1]
score[x + 1] = score[x]
score[x] = temp
# The Sort Array Function
def SortArray():
y = 0
while y < COMPS:
x = 0
while x < COMPS:
if score[x] > score[x + 1]:
#This function not working.
swap()
x += 1
y += 1
#Display Array Function
def displayArray():
x = 0
while x < size:
print(score[x])
x += 1
SortArray()
displayArray()
但插入 swap() 代码,因此 swap() 下的代码并替换它SortArray() 下方,if 条件 下方;就像这样:
def SortArray():
y = 0
while y < COMPS:
x = 0
while x < COMPS:
if score[x] > score[x + 1]:
#This Works
temp = score[x + 1]
score[x + 1] = score[x]
score[x] = temp
x += 1
y += 1
然后它起作用了,所以我想知道为什么在 SortArray()
下没有调用 swap() 函数【问题讨论】:
-
你甚至不需要那个功能。 Python 中的交换可以在没有显式临时变量的单行中完成(不计算隐式创建的元组):
score[x], score[x + 1] = score[x + 1], score[x] -
不建议以这种方式使用全局变量。
-
好的,但这是否意味着swap()不能使用,我想如果我想调用它,它应该可以工作。
-
@SamJereriaManuel 看我的回答。
标签: python-3.x function bubble-sort