Hackerss.com

hackerss
hackerss

Posted on

Ordenar un arreglo usando el mtodo de la burbuja in Java

Ordenar un arreglo usando el mtodo de la burbuja - Java:


/**
* This class implements the bubble sort algorithm.
* @author Juan Carlos Zenteno
* @version 1.0
*/
public class BubbleSort {
   /**
   * This method sort an array of integers.
   * @param array param to sort.
   * @return int[] Obtains the array sorted.
   */   
   public int[] bubbleSort(int[] array) {
       //Variable to store the total sum
       int temp = 0;
       //Sum the two numbers
       for (int i = 0; i < array.length; i++) {
           for (int j = 1; j < (array.length - i); j++) {
               if (array[j - 1] > array[j]) {
                   temp = array[j - 1];
                   array[j - 1] = array[j];
                   array[j] = temp;
               }
           }
       }
       //Return the total
       return array;
   }

   /**
   * One Example
   */
   public static void main(String args[]) throws IOException {

      BubbleSort  bubbleSort= new BubbleSort ();
      //Example
      int[] array = {10, 3, 2, 5, 8, 4, 3, 1, 2, 9, 7, 8}; 
      //Output
      System.out.println("Array Before Bubble Sort");  
      for(int i=0; i < array.length; i++){  
          System.out.print(array[i] + " ");  
      }  

      bubbleSort.bubbleSort(array);//sorting array elements using bubble sort  

      System.out.println("");  

      System.out.println("Array After Bubble Sort");  
      for(int i=0; i < array.length; i++){  
          System.out.print(array[i] + " ");  
      }  

   }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)