00:00

Bubble Sort in Java

Sorting is the process of arranging a list of unsorted data in a particular order, either ascending or descending. Sort algorithms play a very crucial role for organizing unsorted data and facilitating efficient searching, retrieval, and analysis.

Every sorting algorithm has a unique approach for sorting the data; these sorting algorithms are used according to the specific requirements of the problem, including data size, structure, and distribution, as well as time and space constraints.

In this tutorial, we are going to learn all about Bubble Sort in Java.

Java program for implementation of Bubble Sort

BubbleSortExample.java
class BubbleSortExample {
  // A Function to sort an array using Bubble Sort technique
  static void bubbleSort(int array[]) {
    int i, j, temp;
    boolean swapped;
    for (i = 0; i < array.length - 1; i++) {
      swapped = false;
      for (j = 0; j < array.length - i - 1; j++) {
        if (array[j] > array[j + 1]) {

          // Swap array[j] and array[j+1]
          temp = array[j];
          array[j] = array[j + 1];
          array[j + 1] = temp;
          swapped = true;
        }
      }

      // Loop breaks, if no two elements were swapped by inner loop
      if (swapped == false)
        break;
    }
  }

  // Function to print an array
  static void printArray(int array[]) {
    for (int i = 0; i < array.length; i++)
      System.out.print(array[i] + " ");
    System.out.println();
  }

  public static void main(String args[]) {
    // Creates an array
    int array[] = { 40, 70, 90, 20, 80, 100, 60, 10, 30, 50 };
    System.out.println("Created array elements: ");
    // Printing created array elements
    printArray(array);
    // Calling a method to sort an array
    bubbleSort(array);
    System.out.println("\nSorted array elements: ");
    // Printing sorted array elements
    printArray(array);
  }
}
Output
Created array elements:
40, 70, 90, 20, 80, 100, 60, 10, 30, 50

Sorted array elements:
10 20 30 40 50 60 70 80 90 100