Example of Java data structures and algorithms: Bubble Sort

  • 2020-04-01 03:56:56
  • OfStack


 
package al; 
public class BubbleSort { 
   
  public static void main(String[] args) { 
    BubbleSort bubbleSort = new BubbleSort(); 
    int[] elements = { 14, 77, 21, 9, 10, 50, 43, 14 }; 
    // sort the array 
    bubbleSort.sort(elements); 
    // print the sorted array 
    for (int i = 0; i < elements.length; i++) { 
      System.out.print(elements[i]); 
      System.out.print(" "); 
    } 
  } 
   
  public void sort(int[] array) { 
    int i, j; 
    int tmp; 
    for (i = 0; i <= (array.length - 1); i++) { // outer loop 
      for (j = 0; j < (array.length - 1 - i); j++) { // inner loop 
        if (array[j] > array[j + 1]) { 
          tmp = array[j]; 
          array[j] = array[j + 1]; 
          array[j + 1] = tmp; 
        } 
      } 
    } 
  } 
} 


Related articles: