×

Bubble Sort in Java

Bubble Sort in Java

Bubble sort isalso known as sinking sort. It is one of the simplest sorting algorithms. In the bubble sort algorithm, the given array is traversed from left to right. In this sorting algorithm, adjacent elements are swapped when they are present in the wrong order. Thus, initially, the elements of bigger values are placed at their correct position, then the elements of smaller values. The same phenomenon happens in a water tank too, bubbles of bigger size come out first, then the bubbles of smaller size. Hence, this sorting algorithm is called bubble sort.

Algorithm and Pseudo Code

 start BubbleSort(array)
   for all elements of the input array
      if array[index] > array[index + 1]
         swap(array[index], array[index + 1])
      terminate if
   terminate for
   return array
terminate BubbleSort 

Java Program

The following Java program implements Bubble sort on the basis of pseudo-code written above.

FileName: BubbleSortExample.java

 public class BubbleSortExample
{
// method implementing the bubble sort algorithm
static void bubbleSort(int a[], int start, int end)
{
    // outer loop iterates over elements of the array
    for(int i = start; i < end - 1; i++)
    {
        // inner loop does the swapping of elements that are
        // present in wrong order.
        for(int j = 0; j < end - i - 1; j++)
        {
            if(a[j] > a[j + 1])
            {
                // found that current element
                // is greater than the next element
                // hence do the swapping
                int temp = a[j];
                a[j] = a[j + 1];
                a[j + 1] = temp;
            }
        }
    }
}
// main method
public static void main(String argvs[])
{
    // given input array
    int a[] = {67, 78, 34, 12, 30, 6, 9, 21};
    // calculating size of the array
    int size = a.length;
    System.out.println("The array before sorting is: ");
    for(int i = 0; i < size; i++)
    {
       System.out.print(a[i] + " ");
    }
    System.out.println("\n");
    // invoking method bubbleSort()
    bubbleSort(a, 0, size);
    System.out.println("The array after sorting is: ");
    // displaying the sorted array
    for(int i = 0; i < size; i++)
    {
        System.out.print(a[i] + " ");
    }
}
} 

Output:

 The array before sorting is:
67 78 34 12 30 6 9 21
The array after sorting is:
6 9 12 21 30 34 67 78 

Explanation: While writing the outer and inner Java for-loop, to implement bubble sort, care must be taken that the exception java.lang.ArrayIndexOutOfBoundsException is not raised in the program. Consider the following taken from the inner for-loop.

for(int i = start; i < end - 1; i++)

lf – 1 is omitted from the condition, the following exception is raised

Bubble Sort in Java

Therefore, while doing the swapping, these aspects must be taken into consideration. The program is very straightforward. The outer loop iterates over array elements, whereas the inner loop ensures elements are present at the proper position. It is the inner loop that does the actual sorting.

Analysis of Bubble Sort

Bubble sort is a simple and stable algorithm. Since the bubble sort uses two nested for-loop, the bubble sort takes more time than the quick or merge sort. The bubble sort uses the comparison of adjacent elements for doing the sorting. Therefore, this sorting algorithm works well for detecting a very small error in computer graphics (like swapping values of two elements).

Time Complexity

On the basis of above-written code, it is evident that bubble sort does not depend on the arrangements of elements. Therefore, the average, best and worst time complexity of the bubble sort is O(n2), where n is the number of elements present in the array. The high time complexity of bubble sort, O(n2), is due to the nesting of two for-loops. Because of high time complexity, this algorithm is not widely used.

The above-written code can be modified to create dependency on the arrangement of elements.

FileName: BubbleSortExample1.java

 public class BubbleSortExample1
{
// method implementing the bubble sort algorithm
static void bubbleSort(int a[], int start, int end)
{
    // outer loop iterates over elements of the array
    for(int i = start; i < end - 1; i++)
    {
        Boolean flag = true;
        // inner loop does the swapping of elements that are
        // present in wrong order.
        for(int j = 0; j < end - i - 1; j++)
        {
            if(a[j] > a[j + 1])
            {
                // found that current element
                // is greater than the next element
                // hence do the swapping
                int temp = a[j];
                a[j] = a[j + 1];
                a[j + 1] = temp;
                 // swapping has occurred; therefore, iteration of loops should continue.
                flag = false;
            }
        }
        if(flag)
        {
            // the input array is now sorted.
            // Therefore, no need to go further.
            break;
        }
    }
}
// main method
public static void main(String argvs[])
{
    // given input array
    int a[] = {67, 78, 34, 12, 30, 6, 9, 21};
    // calculating size of the array
    int size = a.length;
    System.out.println("The array before sorting is: ");
    for(int i = 0; i < size; i++)
    {
       System.out.print(a[i] + " ");
    }
    System.out.println("\n");
    // invoking method bubbleSort()
    bubbleSort(a, 0, size);
    System.out.println("The array after sorting is: ");
    // displaying the sorted array
    for(int i = 0; i < size; i++)
    {
        System.out.print(a[i] + " ");
    }
}
} 

Output:

 The array before sorting is:
67 78 34 12 30 6 9 21
The array after sorting is:
6 9 12 21 30 34 67 78 

Explanation: The only difference between the previous and the above-written code is the introduction of the flag variable. The flag indicates whether the input array is sorted or not. The flag variable is initialized to the true value, it means the array is sorted. Now, if the inner for-loop finds the wrong order of elements, if block of the inner loop executes, does the swapping of elements and update the value of flag variable from true to false, which means the array is not completely sorted and iteration should continue. If the flag variable retains true even after the execution of the inner loop, the if block after the inner loop executes, and takes the control out of the outer for-loop and thus ruling out the possibility of any further iterations. The following diagram demonstrates the same.

Bubble Sort in Java

The time complexity of the above-written program is still O(n2) for the average and worst cases. However, for the best case (when a sorted array is taken as input), the time complexity reduces from O(n2) to O(n). If required, the above implementation of the bubble sort is used, not the previous one.

Space Complexity

Similar to the quick sort, the space complexity of the bubble sort algorithm is also O(1), that is, constant space complexity. In the above implementations; there is no auxiliary array or any additional space used to do the sorting.


Related Topics

Sylvester Sequence in Java

A Sylvester Sequence is a series of numbers in which each term is the sum of the terms before it plus 1. The sequence's first two terms are 2 and...

3 minutes read.

Java String Interview Questions

Java String Interview Questions String is the most common and important discussed topics in a Java interview. In Java interview interviewer generally asked three to four questions based on String concept....

16 minutes read.

Java Program to Print Permutations of String

A string is given and you need to print all the possible ways for that string. Permutation is arranging the characters of a string to get outputs from the given...

3 minutes read.

Java Constant

A constant is an unchangeable entity in coding, as its title implies. The value which cannot be altered, in other terms. We shall understand about Java constants and exactly how...

3 minutes read.

How to add Elements in Array in Java

Consider an array of the size n, in the given size we must add the elements in the given array. In this tutorial we are preferred to learn how to add...

3 minutes read.

Int vs Integer in Java

In Java, numerical data can be stored using int or Integer. int and Integer both have different definitions but similar usage in Java. What is int in Java? int is a primitive...

4 minutes read.

Java Code Coverage Tools

Code coverage testing is a crucial metric that gauges how thoroughly the program's source code has been tested. The market is flooded with Code Coverage Tools, making it difficult to...

7 minutes read.

Java Read File Line by line

Java provides two options to read files line by line. Each option offers different benefits and has its own set of drawbacks. Following are the ways through which on accomplish...

5 minutes read.

Java Get File Size

There are three ways to get the file size in Java. Using Java InputOutput Using NewInputOutput Library Files.size() Method FileChannel.size() Method Using Apache Commons InputOutput Using Java InputOutput: The Java IO package offers the classes that deal...

5 minutes read.

Various Operation on Queue using Linked List in Java

We keep track of front and rear pointers in a queue data structure. The head of the line points to the first item, and the back to the last. Rear is...

3 minutes read.

Lombok Java

What is Lombok java? A well-liked and widely-used Java framework that is used to reduce or eliminate boilerplate code is called Project Lombok. Both time and effort are saved. We may...

7 minutes read.

Java Lambda foreach

Before understanding lamda foreach, one must know about foreach loop in Java. foreach loop in Java Since J2SE 5.0, there has been a for-each loop in Java, also known as an extended...

4 minutes read.

Java inheritance with Example

Java inheritance Java inheritance is a mechanism in which a child object acquires all the properties and behaviors of a parent object. It helps in reusing the code and establishes...

7 minutes read.

Nth Term of Geometric Progression in Java

There are 3 numbers provided. The geometric progression's initial term is the first number. The second number is the geometric progression's common ratio, and the third number represents the nth...

3 minutes read.

Program to Implement FLAMES Game in Java

Friends, Lovers, Affectionate, Marriage, Enemies, and Sibling are all represented by the acronym FLAMES, which also serves as the name of a well-known game. Although, it can be entertaining to...

4 minutes read.

Java Thread Lifecycle: States and Stages

Multithreading Multithreading is one of the most important features in object-oriented programming, and this multithreading can be implemented by various object-oriented programming languages like Java, Python, and C++. A multithreaded process...

7 minutes read.

Armstrong Number Program in Java

Armstrong Number Program in Java: A positive number is called an Armstrong number if the sum of the cube of each digit is equal to the number itself. There are...

6 minutes read.

Why to use Enum in Java?

In this article, you will be acknowledged about the Enum in java, its uses and mainly its purpose. Enum has various functionalities. Each of them will be discussed. Enum In a computer...

3 minutes read.

How to Convert String to double in Java

How to Convert String to double in java It is used if we have to perform mathematical operations on the string that contains a double number. When we get data from...

3 minutes read.

How to enable java in chrome

The Java module is huge for the Java Runtime Environment (JRE). It permits a program to work with the Java stage to run Java applets. Essentially, each of the undertakings connect...

3 minutes read.