我正在尝试为python创建一个bubble排序方法,只针对pops和grins。但我不认为我的交换方法有效。在
def bubbleSort(list):
length = len(list)
for i in range(length - 1):
if list[i] > list[i+1]:
#swap
swap(list[i], list[i+1])
print(list)
print(list)
def swap(s1, s2):
# assert type(s1) == list and type(s2) == list
# tmp = s1[:]
# s1[:] = s2
# s2[:] = tmp
s2, s1 = s1, s2
程序会显示出我的列表,但每次都不会有任何改变,这说明我的交换方法不起作用。在
严格地说,在您的示例中,将list元素传递到
swap
函数中不会有效果。使用python语法可以直接编写:不知道把这么小的逻辑提取成单独的函数的目的是什么。在
如需了解更多关于评估策略的信息,例如按值调用、按引用调用以及为什么不同,可以查看wiki。在
PPS。正如注释中正确指出的,python的常用评估策略是“Call-by-Sharing”,例如:
相关问题 更多 >
编程相关推荐