Write a Java Program to Implement Bubble Sort algorithm

Bubble Sort is one of the simplest sorting algorithms to understand and implement.

It works by repeatedly swapping adjacent elements in an array if they are in the wrong order until the array is sorted.

In this tutorial, we’ll be implementing Bubble Sort in Java.


The basic idea behind Bubble Sort is to iterate through an array, comparing adjacent elements, and swapping them if they are in the wrong order.

This process is repeated until the entire array is sorted.

Here is the Java code for Bubble Sort:

public class BubbleSort {
   public static void main(String []args) {
      int arr[] = { 5, 2, 7, 3, 1, 8, 6, 4 };
      int n = arr.length;
      int temp = 0;

      for(int i=0; i < n; i++) {
         for(int j=1; j < (n-i); j++) {
            if(arr[j-1] > arr[j]) {
               //swap elements
               temp = arr[j-1];
               arr[j-1] = arr[j];
               arr[j] = temp;
            }
         }
      }

      System.out.println("Sorted Array:");
      for(int i=0; i < n; i++) {
         System.out.print(arr[i] + " ");
      }
   }
}

In this code, we first initialize an array arr with the values we want to sort.

We then get the length of the array using arr.length, which we will use later in the loop.

We also initialize a temporary variable temp that we will use to swap elements.

We then have two nested loops.

The outer loop iterates through the array, and the inner loop compares adjacent elements and swaps them if they are in the wrong order.

The if statement checks if arr[j-1] is greater than arr[j], and if it is, we swap the elements using the temp variable.

Once the sorting is complete, we print out the sorted array using a loop and System.out.print.

That’s all there is to implementing Bubble Sort in Java.

It’s a straightforward algorithm that works well for small arrays.

However, for larger arrays, more efficient sorting algorithms like Quick Sort or Merge Sort should be used.