Sort algorithm is not working!

2

"" " Sort 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?

    
asked by anonymous 25.03.2018 / 19:24

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 going through the array once, ie you are just looping out of the Bubblesort loop.

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]

It's pretty much the same as yours:

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 ordered. So the need for the outermost loop and the not_sorted variable.

This link here has the algorithm explained step-by-step in a very nice way. link

    
25.03.2018 / 19:42
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)

This part of a = x and while is to see if in previous positions have a smaller number, and to change positions. But I'm a beginner, so I do not know if I did it the right way.

    
25.03.2018 / 20:40