Sorting algorithm not working!

Asked

Viewed 116 times

1

""" Arrange the elements of a list in ascending order """

#ordenação bolha

#L = [5,3,1,2,4]

L = [7,4,3,12,8]

x = 0
while x < (len(L) -1):
 if L[x] > L[x+1]:
     L[x],L[x+1] = L[x+1],L[x]

 x += 1

print(L)

Output: [4, 3, 7, 8, 12]

The algorithm is not ordering properly. What is missing?

2 answers

4


Apparently you want to implement Bubblesort. A possible implementation of Bubblesort:

def bubblesort(list):
    not_sorted = True
    while not_sorted:
        not_sorted = False
        for i in range(0, len(list)-1):
            if list[i] > list[i+1]:
                not_sorted = True
                list[i], list[i+1] = list[i+1], list[i]

    return list

print(bubblesort([1, 3, 2, 10, 2, 4]))

The problem with your algorithm is that you are only passing the array once, meaning you are only iterating the loop from outside of Bubblesort.

Notice that part of my code:

for i in range(0, len(list)-1):
    if list[i] > list[i+1]:
        not_sorted = True
        list[i], list[i+1] = list[i+1], list[i]

is pretty much the same as your:

while x < (len(L) -1):
 if L[x] > L[x+1]:
     L[x],L[x+1] = L[x+1],L[x]

The difference is that you have to do this part while the array is not sorted. Hence the need for more out loop and variable not_sorted.

This link here has the algorithm explained step-by-step in a very nice way. http://www.cs.armstrong.edu/liang/animation/web/BubbleSort.html

  • I tried it based on yours but it didn’t work -> https://pastebin.com/Ku2TpTMg

  • You forgot to increment the x. Puts x = x+1 after the line L[x],L[x+1] = L[x+1],L[x], and outside the scope of if.

  • grateful! I’m trying to learn!

  • does not yet work -> https://pastebin.com/1BgUF7Fe

  • for me now the algorithms are the same!

2

I did so:

L = [7,4,3,12,8]

x = 0
while x < (len(L)-1):

  if L[x] > L[x+1]:
    L[x],L[x+1] = L[x+1],L[x]

  a = x      
  while (L[a] < L[a-1]) and (a!=0):
    L[a], L[a-1] = L[a-1],L[a]
    a -= 1

  x += 1

print(L)

That part of a = x and while is to see if in previous positions it has any smaller number, and go changing positions. But I’m a beginner, so I don’t know if I did it properly.

  • https://pastebin.com/1BgUF7Fe

Browser other questions tagged

You are not signed in. Login or sign up in order to post.