1

I'm trying to sort a list by moving through it and checking if a given element of the list is greater than the next element of the list, and if so, moving it accordingly so that the smaller number is to the left, larger to the right.

This is the code I have so far:

L = [3, 4, 1, 5, 2, 0]
for i in range(0, (len(L)-1)):
    if L[i] > L[i+1]:
        L[i], L[i+1] = L[i+1], L[i]
        print(L)

The output of this for the three iterations are as follows:

[3, 1, 4, 5, 2, 0]
[3, 1, 4, 2, 5, 0]
[3, 1, 4, 2, 0, 5]

My goal is to get it to read [0, 1, 2, 3, 4, 5]. I realize I can just use the sorted() function but I'd prefer not to. I was thinking that I could try and iterate the for loop over the list multiple times, but I am unsure as to how to do so.

1

2 Answers 2

1

Currently you only compare each element and it's successor. However you really want to compare it to all following elements (starting with i+1 and ending with len(L)), so you need a double loop:

L = [3, 4, 1, 5, 2, 0]
for i in range(0, (len(L)-1)):
    for j in range(i+1, len(L)):
        if L[i] > L[j]:
            L[i], L[j] = L[j], L[i]
            print(L)

Which prints the following steps:

[1, 4, 3, 5, 2, 0]
[0, 4, 3, 5, 2, 1]
[0, 3, 4, 5, 2, 1]
[0, 2, 4, 5, 3, 1]
[0, 1, 4, 5, 3, 2]
[0, 1, 3, 5, 4, 2]
[0, 1, 2, 5, 4, 3]
[0, 1, 2, 4, 5, 3]
[0, 1, 2, 3, 5, 4]
[0, 1, 2, 3, 4, 5]
Sign up to request clarification or add additional context in comments.

2 Comments

They're completely different sorting methods, he's using bubble sort (albeit incomplete) and you're using insertion sort. You can see the difference in our outputs.
that's actually selection sort IIRC
0

You could just put it inside a while loop:

L = [3, 4, 1, 5, 2, 0]
flag = True
while flag:
    flag = False
    for i in range(0, (len(L)-1)):
        if L[i] > L[i+1]:
            L[i], L[i+1] = L[i+1], L[i]
            flag = True
            print(L)

Output:

[3, 1, 4, 5, 2, 0]
[3, 1, 4, 2, 5, 0]
[3, 1, 4, 2, 0, 5]
[1, 3, 4, 2, 0, 5]
[1, 3, 2, 4, 0, 5]
[1, 3, 2, 0, 4, 5]
[1, 2, 3, 0, 4, 5]
[1, 2, 0, 3, 4, 5]
[1, 0, 2, 3, 4, 5]
[0, 1, 2, 3, 4, 5]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.