Java Program to Implement Bubble Sort

What is Bubble Sort?

Bubble Sort in Java is a simple sorting algorithm that works by repeatedly stepping through the list to be sorted, comparing each pair of adjacent items, and swapping them if they are in the wrong order. Bubble sort technique is used to sort an array of values in increasing or decreasing order.

In simple words, bubble sort algorithm goes with the name, generally used to sort numbers in the ascending order. The smallest numbers bubbles up at each iteration of the sort.

Bubble Sort Algorithm

1. In Bubble sort algorithm we compare the first two elements of an array and swap them if required.
2. If we want to sort the elements of array in ascending order and if the first element is greater than second then, we need to swap the elements.
3. If the first element is smaller than second, we don’t need to swap the elements. This process go on until last and second last element is compared and swapped.

Pseudocode for Bubble Sort in Java
procedure bubbleSort(array: array of integers):
  n = array.length
  for i from 0 to n - 1:
    for j from 0 to n - i - 1:
      if array[j] > array[j + 1]:
        swap(array[j], array[j + 1])
procedure swap(array: array of integers, a: integer, b: integer):
  temp = array[a]
  array[a] = array[b]
  array[b] = temp
Bubble Sort Example:
If we have the array as {50,20,60,90,40}
and we apply bubble sort to sort the array,
then the resultant array after each iteration will be as follows:

               Original array: {50, 20, 60, 90, 40}

After first iteration:   {20, 50, 60, 90, 40}
After second iteration:   {20, 50, 40, 60, 90}
After third iteration:   {20, 40, 50, 60, 90}
After fourth iteration:  {20, 40, 50, 60, 90}
               Sorted array is  20  40  50  60 90
Program/Source Code

Here is the source code of the Java Program to Implement Bubble Sort. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

  1. //This is a java program to sort numbers using bubble sort
  3. import java.util.Random;
  5. public class Bubble_Sort 
  6. {
  7.     static int[] sort(int[] sequence) 
  8.     {
  9.         // Bubble Sort
  10.         for (int i = 0; i < sequence.length; i++)
  11.             for (int j = 0; j < sequence.length - 1; j++)
  12.                 if (sequence[j] > sequence[j + 1]) 
  13.                 {
  14.                     sequence[j] = sequence[j] + sequence[j + 1];
  15.                     sequence[j + 1] = sequence[j] - sequence[j + 1];
  16.                     sequence[j] = sequence[j] - sequence[j + 1];
  17.                 }
  18.         return sequence;
  19.     }
  21.     static void printSequence(int[] sorted_sequence) 
  22.     {
  23.         for (int i = 0; i < sorted_sequence.length; i++)
  24.             System.out.print(sorted_sequence[i] + " ");
  25.     }
  27.     public static void main(String args[]) 
  28.     {
  29.         System.out
  30.                 .println("Sorting of randomly generated numbers using BUBBLE SORT");
  31.         Random random = new Random();
  32.         int N = 20;
  33.         int[] sequence = new int[N];
  35.         for (int i = 0; i < N; i++)
  36.             sequence[i] = Math.abs(random.nextInt(1000));
  38.         System.out.println("\nOriginal Sequence: ");
  39.         printSequence(sequence);
  41.         System.out.println("\nSorted Sequence: ");
  42.         printSequence(sort(sequence));
  43.     }
  44. }
Program Explanation

1. This program uses the Bubble Sort algorithm to sort a randomly generated array of 20 integers.
2. The program defines a class called Bubble_Sort, which contains a static method called sort that takes an integer array as input and returns a sorted array.
3. The program also defines a static method called printSequence that prints an array of integers.
4. The main method generates a random array of 20 integers, prints the original sequence, sorts the sequence using the sort method, and prints the sorted sequence using the printSequence method.


Time Complexity: O(n2)
The time complexity of the bubble sort algorithm is O(n2).

Space Complexity: O(1)
The space complexity of bubble sort program is constant because no extra space is required.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
Program Output

In this case, we are sorting of randomly generated numbers using bubble sort in ascending order.

$ javac
$ java Bubble_Sort
Sorting of randomly generated numbers using BUBBLE SORT
Original Sequence: 
307 677 574 88 325 851 676 357 172 932 166 450 60 538 964 987 706 690 919 518 
Sorted Sequence: 
60 88 166 172 307 325 357 450 518 538 574 676 677 690 706 851 919 932 964 987
Advantages of Bubble Sort in Java:
  • Simple implementation and easy to understand.
  • Requires minimal additional space, making it memory-efficient.
  • Suitable for small datasets or when simplicity is prioritized.
  • Suitable for beginners to learn sorting algorithms.
Disadvantages of Bubble Sort in Java:
  • Inefficient for large datasets, becoming slower as the size increases.
  • Lacks adaptability to partially sorted data, resulting in unnecessary comparisons and swaps.
  • Slower compared to more efficient sorting algorithms like merge sort or quicksort.
  • Limited scalability and performance compared to other sorting algorithms.
FAQs about Bubble Sort

1. What is Bubble Sort in Java?
Bubble Sort is a simple sorting algorithm that repeatedly compares adjacent items and swaps them if they are in the wrong order. It keeps iterating through the list until the entire array is sorted.

2. How does Bubble Sort work in Java?
Bubble Sort works by repeatedly swapping adjacent elements if they are in the wrong order. It starts at the beginning of the array and compares each pair of adjacent elements, swapping them if necessary. This process continues until the array is sorted.


3. What is the time complexity of Bubble Sort in Java?
The time complexity of Bubble Sort is O(n2) in the average and worst-case, where ‘n’ is the number of elements in the array. This means that the time taken by bubble sort increases exponentially with the size of the input.

4. Is Bubble Sort efficient for large datasets in Java?
No, Bubble Sort is not efficient for large datasets. It becomes increasingly slower as the size of the dataset grows. Its time complexity makes it significantly less efficient compared to more optimized sorting algorithms like merge sort or quicksort.

5. When should I use Bubble Sort in Java?
Bubble Sort can be used when simplicity and ease of implementation are prioritized over performance. It is beneficial as a learning tool for beginners to grasp the concepts of sorting algorithms. However, for practical purposes or sorting large datasets, it is advisable to opt for more efficient sorting algorithms that can handle larger data sizes more effectively.

To practice programs on every topic in Java, please visit “Programming Examples in Java”, “Data Structures in Java” and “Algorithms in Java”.


Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.