×

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

Java Switch Keyword

In this article we are going to learn the concept of a java switch keyword. Generally, java case keyword is used with the switch statements or keyword.Switch keyword is implemented in...

3 minutes read.

Method Overriding in Java

Overriding  Overriding is also known as run time polymorphism, and it is about the same method with the same signatures in different classes. Overriding can be applied only methods. Method Overriding Method Overriding...

8 minutes read.

Sealed Class in Java

What is a Sealed Class in Java? In programming, the two main issues that must be taken into account when creating an application are security and control flow. The use of...

5 minutes read.

Nonagonal number in Java

Figureate numbers with the form n(7n-5)/2 are known as nonagonal numbers. 7n+3 will be a triangular number if n is a nonagonal number. The nonagon is included in the idea...

4 minutes read.

Best Practices to use String Class in Java

Use String Builder or String Buffer for String concatenation in place of + operator.Compare two strings by equals( ) method instead == operator.Call .equals( ) method on a known String...

3 minutes read.

Reserved Keywords in Java

In Java, a reserved term is used as a code key called a keyword. Because they are predefined, these terms cannot be used for anything else. They cannot serve as...

3 minutes read.

Static Array in Java

In this tutorial, we will study static arrays in Java. An array is a data structure that is of great importance in any programming language. It is classified into two...

3 minutes read.

Compile time vs Runtime in java

Introduction: This article will discuss compile time vs. runtime in java. Compile time and runtime are two programming terms utilized in software improvement. Compile time is when the source code is...

3 minutes read.

Program to find the duplicate characters in a string

Problem statement You have given with a string and your task is to find out the repeated characters from the string and print them. If no character is repeated, then you...

2 minutes read.

Transaction Management in java

Definition: A database application is an application that is running against a relational database and executes one or more transactions. A transaction is an executing program that contains some database operations,...

4 minutes read.

Java Double Keyword

In java primitive data types, we have two different types of data types which are Boolean and floating-point data types.In floating data type again we have four types which are...

3 minutes read.

Console Errors in Java

An unlawful motion taken through the person that reasons this system to act abnormally is amistake until this system is compiled or run; maximum programming mistakes pass unnoticed.The software is...

3 minutes read.

How to check the Java version in cmd

To make programs that can run on our systems, we need to install programming language-related software in our systems. Different programming languages require different types of software, aka IDEs (Integrated...

5 minutes read.

File Operation in Java

In Java, a file is an Abstract data type. These are used to store the data which is related. Files are named storage locations. With a file we can perform...

7 minutes read.

How to Convert Date to String in Java

How to Convert Date to String in Java We need to convert Date to String in Java may for displaying purpose. We can convert Date to String in Java using the format() method of java.text.DateFormat class. There...

2 minutes read.

Java 9 Interface Private Method

Java 9 provides us the facility to include private methods inside the java interface. In java 8 and earlier versions, we are supposed to use only constant variables and abstract...

3 minutes read.

Java Math cos() Method

The cos() method of Math class returns the trigonometric cosine of the specified angle. Syntax: public static double cos(double a) Parameters: The parameter ‘a’ represents an angle measured in radians. Return Value: The cos() method returns...

1 minute read.

Java Command not found

Java Command not found error is displayed if Java is not installed on the computer or if the command prompt cannot find Java.exe to run the program. Our Java software...

3 minutes read.

Java Tokens

Classes and methods are included in the Java program. The procedures also provide the expressions and statements required to finish a specific operation. Tokens make up the sentences and expressions...

4 minutes read.

Java String Inbuilt functions

There are different types of inbuilt functions available in the Java String class, all of them are listed below. Char chat At (int index)It outputs the character indicated by the index....

5 minutes read.