Created
June 28, 2023 00:31
-
-
Save henriquesebastiao/a49671bbff7ba9796af0e9f70a4b1e34 to your computer and use it in GitHub Desktop.
Algoritmo Bubble Sort em Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def bubble_sort(array): | |
| """Ordena uma lista usando o algoritmo de bolha.""" | |
| n = len(array) | |
| for i in range(n): | |
| # Cria uma flag que irá permitir o algoritmo parar se não houver trocas | |
| already_sorted = True | |
| # Itera sobre todos os elementos da lista | |
| # (exceto o último, pois o algoritmo de bolha compara os elementos atuais com o próximo) | |
| for j in range(n - i - 1): | |
| if array[j] > array[j + 1]: | |
| # Se o elemento atual for maior que o próximo, troca os dois | |
| array[j], array[j + 1] = array[j + 1], array[j] | |
| # Como houve uma troca, o algoritmo não está ordenado corretamente | |
| already_sorted = False | |
| # If there were no swaps during the last iteration, | |
| # the array is already sorted, and we can terminate | |
| if already_sorted: | |
| break | |
| # Testando o algoritmo | |
| if __name__ == "__main__": | |
| user_input = input("Digite uma lista de números SEPARADOS POR ESPAÇOS: ") | |
| unsorted = [int(item) for item in user_input.split(" ")] | |
| print(unsorted) # Imprime a lista antes da ordenação | |
| bubble_sort(unsorted) # Ordena a lista usando o algoritmo de bolha | |
| print(unsorted) # Imprime a lista depois da ordenação |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment