简体   繁体   中英

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. 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. When you finish the inner loop you increment i of 1 and everything that is before i is already sorted. 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM