Bubble Sort in Java


Bubble Sort is the simplest algorithm for sorting elements. In the Bubble sort algorithm, the array is traversed by comparing the current element with the next element each time. If the current element is greater than the next element then the positions will be swapped in this way the array will be sorted. As the complexity of this algorithm is Ο(n2) where n is the number of elements. This algorithm can not be used for large datasets. In this article, you are going to learn the Bubble sort algorithm program in Java.

Program

Following is the program for performing Bubble sort in Java.

public class MyBubbleSort {
    
   public static void main(String[] args) {
       
      // array of items to be sorted
      int items[] = { 22, -45, 38, 10, -1, 73, 90, 0, -6, 7 };
      
      System.out.println("Bubble Sort Program: \n");
      
      // printing array elements before sorting
      System.out.println("Items Before Sorting Array: ");
      for(int i = 0; i < items.length; i++) {
         System.out.print(items[i] + "  ");
      }
      System.out.println("\n");
      
      // Performing Bubble Sort
      int n = items.length;
      int temp = 0;

      for(int i = 0; i < n; i++) {
         for(int j=1; j < (n-i); j++) { if(items[j-1] > items[j]) {
               temp = items[j-1];
               items[j-1] = items[j];
               items[j] = temp;
            }
         }
      }
      // end of bubble sort
      
      // printing array elements after sorting
      System.out.println("Array After Bubble Sort");
      for(int i = 0; i < items.length; i++) {
         System.out.print(items[i] + "  ");
      }
   }
}

The output should be:

Bubble Sort Program:

Items Before Sorting Array:
22 -45 38 10 -1 73 90 0 -6 7

Array After Bubble Sort
-45 -6 -1 0 7 10 22 38 73 90