Bubble Sort in Java

We apply sorting techniques in many aspects of real life. You might think that it is simple logic. You can even ask why a computer algorithm needs to solve it. The answer to this is that it becomes hectic for a human to sort when abundant numbers are involved. This is where computer algorithms lend us a helping hand.

And what’s more interesting is that there are various algorithms to sort a set of elements in Java. They vary according to the time and space complexities though the result is the same. This article will give you a clear idea of bubble sort in Java.

What is bubble sort?

Bubble sort is an algorithm used for sorting. It compares the current value with the adjacent values in the array and swaps if the element on the left is larger than that of the one on the right. Bubble sort is said to be one of the simplest sorting algorithms.

Do you know how the term sorting came to be? Here is the explanation for it. It was termed as Bubble sort as at the end of each iteration, the biggest number settles at the bottom of the array in the same way as the heaviest bubble settles down in a vessel. Then, the elements are swapped until the array is completely sorted.

Though it primarily applies to ascending-order sorting, we can also use it to do the reverse. In such a case, the smallest element will stay at the end of the array in every iteration. This takes place when we inverse the weight of the elements.

It falls under the category of an in-place sorting algorithm. It means that no extra space is required, and the array itself gets modified while being sorted.

Working of Bubble Sort in Java:

Bubble Sort in Java works in an array. Here is a diagram with a small set of elements to make you understand its works.

java bubble sorting

bubble sorting

java bubble sort

bubble sort

Points to note:

Here are some essential points to note when you are working with bubble sort in Java:

1. The Best case complexity of Bubble Sort is 0(n). Here, n is the total number of elements in the array. Best Case complexity only occurs when the given array is already sorted.

2. The Worst-case complexity and Average case complexity of a Bubble Sort is 0(n2). Here, n is the total number of elements in an array.

3. As mentioned before, Bubble Sort belongs to the category of in-place sorting.

4. The Auxiliary space that the Bubble Sort consumes is 0(1).

5. Bubble Sort is a stable algorithm.

Code to implement Bubble Sort in Java – Ascending order:

public class BubbleSortAsc {
  static void bubbleAscending(int[] arr) {
    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]) {
          temp = arr[j - 1];
          arr[j - 1] = arr[j];
          arr[j] = temp;
        }
      }
    }
  }
  public static void main(String[] args) {
    int arr[] = { 2, 5, 1, 8 , 9, 6, 4 };
    System.out.println("Array to implement Bubble Sort: ");
    for (int i = 0; i < arr.length; i++) {
      System.out.print(arr[i] + " ");
    }
    System.out.println();
    bubbleAscending(arr);   
    System.out.println("Sorted Array: ");
    for (int i = 0; i < arr.length; i++) {
      System.out.print(arr[i] + " ");
    }
  }
}

Output:
Array to implement Bubble Sort: 2, 5, 1, 8, 9, 6, 4
Sorted Array: 1, 2, 4, 5, 6, 8, 9

Explanation of the code:

Step 1: To create a method for bubble sort, we will use the ‘bubbleAscending’ method. It takes the input value as an array of elements and stores it in ‘arr’. The length of the array is ‘arr.length’.

Step 2: An outer for loop is created to iterate over each array element.

Step 3: The inner for loop begins from the first element of the array till the second element from the last (arr.len – i – 1).

Each time an index is reduced, the previous is traversed at the end of each iteration, and the largest element for that iteration reaches the end.

Step 4: Inside the nested for loop, the if condition statement checks if the element on the left is greater than the element on the right. If yes, swapping takes place.

Step 5: The outer loop will finally iterate all the elements even if the array is completely sorted and ensure the output is a perfectly sorted array.

Code to implement Bubble Sort in Java – Descending order

public class BubbleSortDesc {
  static void bubbleDescending(int[] arr) {
    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]) {
          temp = arr[j - 1];
          arr[j - 1] = arr[j];
          arr[j] = temp;
        }
      }
    }
  }
  public static void main(String[] args) {
    int arr[] = {2, 5, 1, 8, 9, 6, 4};
    System.out.println("Array to implement Bubble Sort: ");
    for (int i = 0; i < arr.length; i++) {
      System.out.print(arr[i] + " ");
    }
    System.out.println();
    bubbleDescending(arr); 
    System.out.println("Sorted Array: ");
    for (int i = 0; i < arr.length; i++) {
      System.out.print(arr[i] + " ");
    }
  }
}

Output:
Array to implement Bubble Sort: 2, 5, 1, 8, 9, 6, 4
Sorted Array: 9, 8, 6, 5, 4, 2, 1

Advantages of Bubble Sort in Java:

  • Bubble Sort is one of the simplest algorithms to understand.
  • It does not require many lines of code compared to the other algorithms.
  • Memory space is saved to a greater extent. This technique does not involve extra space. It is an in-place sorting technique.

Disadvantages of java Bubble Sort:

  • It takes quite a lot of time to sort the elements.
  • The average time complexity increases with the increase in the count of elements in the array.

Conclusion:

This is everything about the Bubble Sort in Java. This sorting technique is applied in computer graphics to find a tiny error in almost-sorted arrays and fix it with linear complexity (2n). You can also perform sorting using other sorting techniques to see which method is easier for you.

Leave a Reply

Your email address will not be published. Required fields are marked *