[英]Why doesn't this sorting method work in Python?
I've got this code to sort a list without using the sorted function in python. 我有这段代码可以对列表进行排序,而无需在python中使用sorted函数。 The output is the opposite to what is expected (largest to smallest rather than smallest to largest)
输出与预期相反(从最大到最小而不是从最小到最大)
Changing the < to a > seems to help but im not sure why this is 将<更改为>似乎有帮助,但是我不确定为什么会这样
lista=[2,1,5,1,3,6]
for i in range(len(lista)):
for l in range(len(lista)):
if i==l:
continue
if lista[l]<lista[i]:
temp=lista[i]
lista[i]=lista[l]
lista[l]=temp
print(lista)
expected output list that is smalled to largest, but getting the opposite unless I change the < sign to a > sign, but I'm not sure why this is? 预期输出列表,该列表将变小到最大,但是得到相反的结果,除非我将<符号更改为>符号,但是我不确定为什么会这样?
Try to write on paper every iteration of your algorithm: 尝试在纸上写算法的每个迭代:
i = 0: 2 1 5 1 3 6
i = 1: 1 2 5 1 3 6
i = 2: 2 1 5 1 3 6
your issue is that the inner loop for l in range(len(lista)):
start every time from 0, but instead you have to start from position i. 您的问题是
for l in range(len(lista)):
的内部循环for l in range(len(lista)):
每次从0开始,但是您必须从位置i开始。 When you finish the inner loop you increment i of 1 and everything that is before i is already sorted. 当您完成内部循环时,将i递增1,然后对i进行排序之前的所有内容。 If the inner loop restart from the begin like in this case you will have that 1 is less than 2 (on i = 1) you swap it again.
如果这种情况下内部循环从头开始重新启动,则您将获得1小于2(在i = 1上),请再次交换它。
lista=[2,1,5,1,3,6]
for i in range(len(lista)):
for l in range(i, len(lista)):
if i==l:
continue
if lista[l]<lista[i]:
temp=lista[i]
lista[i]=lista[l]
lista[l]=temp
I recommend you to read about insertion sort and selection sort to learn better this algorithm. 我建议您阅读有关插入排序和选择排序的信息,以更好地学习此算法。
The problem is that the second loop goes through the entire list again. 问题是第二个循环再次遍历整个列表。 What you'd want to do is to look at the remaining elements instead:
您要做的是改为查看其余元素:
lista = [2, 1, 5, 1, 3, 6]
for i in range(len(lista)):
# change range to start at i
for l in range(i, len(lista)):
if i == l:
continue
if lista[l] < lista[i]:
temp = lista[i]
lista[i] = lista[l]
lista[l] = temp
edit: To be more specific, think about what happens on the last iteration of the outer loop. 编辑:更具体地说,考虑一下外循环的最后一次迭代会发生什么。
lista[i]
will be the last spot on the list, and you're swapping each time lista[l]
is smaller, so in the end you have the smallest number as the last one. lista[i]
将是列表上的最后一个位置,并且每次lista[l]
较小时都会交换一次,因此最后您拥有最小的数字作为最后一个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.