Bubble Sort Source Code in Java

In this source code example, we will write a Java program to demonstrate how to implement the Bubble Sort algorithm in Java.

Bubble sort is a simple sorting algorithm that works by repeatedly iterating through the list and swapping adjacent elements that are out of order. The algorithm repeats this process until the list is fully sorted.

Bubble Sort Source Code in Java

public class BubbleSort {

   public void printArray(int[] arr) {
      int n = arr.length;
      for (int i = 0; i < n; i++) {
         System.out.print(arr[i] + " ");
      }
      System.out.println();
   }

   public void sort(int[] arr) {
      int n = arr.length;
      boolean isSwapped;

      for (int i = 0; i < n - 1; i++) {
         isSwapped = false;
         for (int j = 0; j < n - 1 - i; j++) {
            if (arr[j] > arr[j + 1]) {
               int temp = arr[j];
               arr[j] = arr[j + 1];
               arr[j + 1] = temp;
               isSwapped = true;
            }
         }
         if (isSwapped == false) {
            break;
         }

      }

   }

   public static void main(String[] args) {
      int[] arr = new int[] { 5, 1, 2, 9, 10 };
      BubbleSort bs = new BubbleSort();
      bs.printArray(arr);
      bs.sort(arr);
      bs.printArray(arr);

   }
}

Output:

5 1 2 9 10 
1 2 5 9 10 
Bubble sort has a time complexity of O(n^2), making it less efficient than other sorting algorithms for large lists. However, it is simple to implement and can be useful for small lists or as a reference implementation.

Comments