Programa Java para implementar el algoritmo de clasificación de burbujas

En este ejemplo, aprenderemos a ejecutar el algoritmo de clasificación de burbujas en Java.

Para comprender este ejemplo, debe tener el conocimiento de los siguientes temas de programación de Java:

  • Métodos Java
  • Java para Loop
  • Matrices de Java

Ejemplo: Programa Java para implementar el algoritmo de clasificación de burbujas

 // import the Class import java.util.Arrays; import java.util.Scanner; class Main ( // create an object of scanner // to take input from the user Scanner input = new Scanner(System.in); // method to perform bubble sort void bubbleSort(int array()) ( int size = array.length; // for ascending or descending sort System.out.println("Choose Sorting Order:"); System.out.println("1 for Ascending 2 for Descending"); int sortOrder = input.nextInt(); // run loops two times // first loop access each element of the array for (int i = 0; i < size - 1; i++) // second loop performs the comparison in each iteration for (int j = 0; j  array(j + 1)) ( // swap if left element is greater than right int temp = array(j); array(j) = array(j + 1); array(j + 1) = temp; ) ) // sort the array in descending order else ( // compares the adjacent element if (array(j) < array(j + 1)) ( // swap if left element is smaller than right int temp = array(j); array(j) = array(j + 1); array(j + 1) = temp; ) ) ) // driver code public static void main(String args()) ( // create an array int() data = ( -2, 45, 0, 11, -9 ); // create an object of Main class Main bs = new Main(); // call the method bubbleSort using object bs // pass the array as the method argument bs.bubbleSort(data); System.out.println("Sorted Array in Ascending Order:"); // call toString() of Arrays class // to convert data into the string System.out.println(Arrays.toString(data)); ) ) 

Salida 1

 Elija Orden de clasificación: 1 para ascendente 2 para descendente 1 Matriz ordenada: (-9, -2, 0, 11, 45)

En este caso, hemos ingresado 1 como entrada. Por lo tanto, el programa clasifica la matriz en orden ascendente.

Salida 2

 Elija Orden de clasificación: 1 para ascendente 2 para descendente 2 Matriz ordenada: (45, 11, 0, -2, -9)

En este caso, hemos ingresado 2 como entrada. Por lo tanto, el programa clasifica la matriz en orden descendente.

Si desea obtener más información sobre el algoritmo de clasificación de burbujas, visite Algoritmo de clasificación de burbujas.

Nota : hemos utilizado Java Scanner Class para recibir información del usuario.

Articulos interesantes...