Programma Bubble Sort in Java: ESEMPIO di algoritmo di ordinamento

Sommario:

Anonim

Cos'è Bubble Sort?

Bubble sort è un semplice algoritmo che confronta il primo elemento dell'array con quello successivo. Se l'elemento corrente dell'array è numericamente maggiore di quello successivo, gli elementi vengono scambiati. Allo stesso modo, l'algoritmo attraverserà l'intero elemento dell'array.

In questo tutorial creeremo un programma JAVA per implementare Bubble Sort. Controlla l'output del codice che ti aiuterà a capire la logica del programma

pacchetto com.guru99;public class BubbleSort {public static void main (String [] args){int arr [] = {860,8,200,9};System.out.println ("--- Array BEFORE Bubble Sort ---");printArray (arr);bubbleSort (arr); // ordina gli elementi dell'array usando il bubble sortSystem.out.println ("--- Array DOPO Bubble Sort ---");printArray (arr);}static void bubbleSort (int [] array){int n = array.length;int temp = 0;for (int i = 0; i  matrice [j]){// scambia elementitemp = array [j-1];matrice [j-1] = matrice [j];array [j] = temp;System.out.println (array [j] + "è maggiore di" + array [j-1]);System.out.println ("Scambio di elementi: nuovo array dopo lo scambio");printArray (array);}}}}static void printArray (int [] array) {for (int i = 0; i 

Produzione:

860 8 200 9Sort Pass Number 1Comparing 860 and 8860 is greater than 8Swapping Elements: New Array After Swap8 860 200 9Comparing 860 and 200860 is greater than 200Swapping Elements: New Array After Swap8 200 860 9Comparing 860 and 9860 is greater than 9Swapping Elements: New Array After Swap8 200 9 860Sort Pass Number 2Comparing 8 and 200Comparing 200 and 9200 is greater than 9Swapping Elements: New Array After Swap8 9 200 860Sort Pass Number 3Comparing 8 and 9Sort Pass Number 4---Array AFTER Bubble Sort---8 9 200 860