Bubble Sort algorithm error in Python

Asked

Viewed 110 times

0

Currently I have studied a little Python and, amid the studies I am trying to perform a challenge where I need to implement a Bubble Sort algorithm in Python. The criteria are:

  1. The algorithm receives a string as input and sorts the given values.
  2. This string must be separated by blanks
  3. Input: integra 10 8 2 3 5 1' Output: pra 1 2 3 5 8 10'

I implemented the algorithm below, but what I have received as output is: ['1', '10', '2', '3', '5', '8']

I can’t see the error in my logic, if anyone can help me how to solve this and point out where my mistake is.

def sort(array):

    for final in range(len(array), 0, -1):
        exchanging = False

        for current in range(0, final - 1):
            if array[current] > array[current + 1]:
                array[current + 1], array[current] = array[current], array[current + 1]
                exchanging = True

        if not exchanging:
            break

array = sorted(['10', '8', '2', '3', '5', '1']) # entrada: 10 8 2 3 5 1 saída: ‘1 2 3 5 8 10’
sort(array)
print(array)

3 answers

1

Your code is correct, the problem is that you are using strings. Strings are not compared numerically but alphabetically, because they can contain letters and other characters... So '10' is actually smaller than '2', as well as 'ba' is less than 'c'.

Therefore, the order is correct, verbatim... If you want to compare the numerical value, you would have to use integers, for example:

if int(array[current]) > int(array[current + 1])

0

If you wish sort out values it makes no sense to capture strings. So it is more convenient to directly capture the numerical value.

I realized that the values you are working on are integer, so I developed the following algorithm to solve your question...

# Algoritmo de ordenação "Bubble Sort".
def bubble_sort(array):
    fim = len(array)
    while fim > 0:
        i = 0
        # Percorrendo o vetor de "0" até "fim".
        while i < fim - 1:
            # Realizando a troca da posição atual pela próxima.
            if array[i] > array[i + 1]:
                temp = array[i]
                array[i] = array[i + 1]
                array[i + 1] = temp
            i += 1
        fim -= 1
    print(f'\033[32mO vetor ordenado é: {array}')


vetor = [10, 8, 2, 3, 5, 1]
bubble_sort(vetor)
print()

Note that this algorithm is working with a list fixa, of whole numbers, which in this case is ...

vetor = [10, 8, 2, 3, 5, 1]

Also note that this algorithm goes through the given list and then sorts its integer values.

Now, if you wish to run bubble sort in any lists, you can use the following algorithm...

# Algoritmo de ordenação "Bubble Sort".
def bubble_sort(array):
    fim = len(array)
    while fim > 0:
        i = 0
        # Percorrendo o vetor de "0" até "fim".
        while i < fim - 1:
            # Realizando a troca da posição atual pela próxima.
            if array[i] > array[i + 1]:
                temp = array[i]
                array[i] = array[i + 1]
                array[i + 1] = temp
            i += 1
        fim -= 1
    print(f'\033[32mO vetor ordenado é: {array}')


vetor = list(map(int, input('Digite os valores do array: ').split()))
bubble_sort(vetor)
print()

This second algorithm is prompted to enter the values of the respective vector.

OBSERVING: At the time of the values request, you have to type all the values in the same row as the input, separated by um só espaço. After entering all values, press the key Enter.

At this time the algorithm will perform the entire sorting task.

-1

I did so

def swap( array, i, j ):
    tmp = array[ i ]
    array[ i ] = array[ j ]
    array[ j ] = tmp

def bubble( array ):
    for i in range( 0, len( array ) ):
        for j in range( len( array ), i + 1, -1 ):
            if array[ j ] > array[ j - 1]:
                swap( array, j, j - 1 )

Browser other questions tagged

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