Como implementar o algoritmo Bubble Sort em Java – Exemplo de ordem crescente e decrescente
Publicados: 2019-01-19
Bubble sort
, às vezes incorretamente chamado de sinking sort
, é um algoritmo de classificação simples que funciona percorrendo repetidamente a lista a ser classificada, comparando cada par de itens adjacentes e trocando-os se estiverem na ordem errada.
A passagem pela lista é repetida até que nenhuma troca seja necessária, o que indica que a lista está ordenada. O algoritmo recebe o nome da forma como os elementos menores bubble
para o topo da lista.
Como ele usa apenas comparações para operar em elementos, é uma classificação por comparação. Embora o algoritmo seja simples, a maioria dos outros algoritmos de ordenação são mais eficientes para listas grandes.
A lógica é simples:
Na ordenação por bolhas, basicamente percorremos a lista de matrizes da primeira até a posição (tamanho – 1) e comparamos o elemento com o próximo. Troque Elemento pelo próximo elemento somente se o próximo elemento for maior.
Aqui está um código Java:
- Crie o arquivo
CrunchifyBubbleSort.java
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
package crunchify . com . tutorials ; import java . util . Arrays ; /** * @author Crunchify.com * How to Implement Bubble sort algorithm in Java? Ascending and Descending Order Tutorial */ public class CrunchifyBubbleSort { public static void main ( String [ ] args ) { int [ ] crunchifyArray = { 15 , 3 , 9 , 7 , 19 , 8 , 1 , 5 } ; int [ ] crunchifyArrayDesc = { 20 , 13 , 19 , 37 , 69 , 18 , 21 , 5 , 99 } ; crunchifyPrint ( "Let's get started on Bubble Sort implementation in Java - by Crunchify \n" ) ; crunchifyPrint ( "============ Ascending Order result: " + Arrays . toString ( CrunchifyBubbleSortAscMethod ( crunchifyArray ) ) + "\n" ) ; crunchifyPrint ( "============ Descending Order result: " + Arrays . toString ( CrunchifyBubbleSortDescMethod ( crunchifyArrayDesc ) ) + "\n" ) ; } // Bubble Sort Algorithm in Ascending Order public static int [ ] CrunchifyBubbleSortAscMethod ( int [ ] crunchifyArr ) { for ( int i = 0 ; i < crunchifyArr . length - 1 ; i ++ ) { for ( int j = 1 ; j < crunchifyArr . length - i ; j ++ ) { if ( crunchifyArr [ j - 1 ] > crunchifyArr [ j ] ) { int temp = crunchifyArr [ j - 1 ] ; crunchifyArr [ j - 1 ] = crunchifyArr [ j ] ; crunchifyArr [ j ] = temp ; } } crunchifyPrint ( "Iteration " + ( i + 1 ) + ": " + Arrays . toString ( crunchifyArr ) ) ; } return crunchifyArr ; } // Bubble Sort Algorithm in Descending Order public static int [ ] CrunchifyBubbleSortDescMethod ( int [ ] crunchifyArr ) { for ( int i = 0 ; i < crunchifyArr . length - 1 ; i ++ ) { for ( int j = 1 ; j < crunchifyArr . length - i ; j ++ ) { if ( crunchifyArr [ j - 1 ] < crunchifyArr [ j ] ) { int temp = crunchifyArr [ j - 1 ] ; crunchifyArr [ j - 1 ] = crunchifyArr [ j ] ; crunchifyArr [ j ] = temp ; } } crunchifyPrint ( "Iteration " + ( i + 1 ) + ": " + Arrays . toString ( crunchifyArr ) ) ; } return crunchifyArr ; } // Simple log util private static void crunchifyPrint ( String result ) { System . out . println ( result ) ; } } |
Resultado do Console do Eclipse:
Basta executar acima do programa java Bubble Sort no console do Eclipse ou no IntelliJ IDE e você deverá ver o resultado abaixo.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
Let ' s get started on Bubble Sort implementation in Java - by Crunchify Iteration 1 : [ 3 , 9 , 7 , 15 , 8 , 1 , 5 , 19 ] Iteration 2 : [ 3 , 7 , 9 , 8 , 1 , 5 , 15 , 19 ] Iteration 3 : [ 3 , 7 , 8 , 1 , 5 , 9 , 15 , 19 ] Iteration 4 : [ 3 , 7 , 1 , 5 , 8 , 9 , 15 , 19 ] Iteration 5 : [ 3 , 1 , 5 , 7 , 8 , 9 , 15 , 19 ] Iteration 6 : [ 1 , 3 , 5 , 7 , 8 , 9 , 15 , 19 ] Iteration 7 : [ 1 , 3 , 5 , 7 , 8 , 9 , 15 , 19 ] ============ Ascending Order result : [ 1 , 3 , 5 , 7 , 8 , 9 , 15 , 19 ] Iteration 1 : [ 20 , 19 , 37 , 69 , 18 , 21 , 13 , 99 , 5 ] Iteration 2 : [ 20 , 37 , 69 , 19 , 21 , 18 , 99 , 13 , 5 ] Iteration 3 : [ 37 , 69 , 20 , 21 , 19 , 99 , 18 , 13 , 5 ] Iteration 4 : [ 69 , 37 , 21 , 20 , 99 , 19 , 18 , 13 , 5 ] Iteration 5 : [ 69 , 37 , 21 , 99 , 20 , 19 , 18 , 13 , 5 ] Iteration 6 : [ 69 , 37 , 99 , 21 , 20 , 19 , 18 , 13 , 5 ] Iteration 7 : [ 69 , 99 , 37 , 21 , 20 , 19 , 18 , 13 , 5 ] Iteration 8 : [ 99 , 69 , 37 , 21 , 20 , 19 , 18 , 13 , 5 ] ============ Descending Order result : [ 99 , 69 , 37 , 21 , 20 , 19 , 18 , 13 , 5 ] Process finished with exit code 0 |
O que é uma complexidade de tempo do algoritmo de classificação de bolhas?
- Se você considerar o
Best case
cenário, então seriaO(n)
- Se você considerar o
Worst case
cenário, então seriaO(n 2 )
Deixe-me saber se você tiver algum problema ou exceção executando o programa acima.