Bubble Sort Program in Java – Explained with Examples

Updated on September 20, 2024

Article Outline

In this article, we will learn about the bubble sort algorithm and how to implement it step by step in the Java programming language. Bubble Sort is one of the simplest algorithms to understand and implement. This article will explore the bubble sort, its mechanics, and its implementation in Java and provide some examples to solidify our understanding.

What is Bubble Sort?

The simplest sorting algorithm repeatedly steps through the list or array. This algorithm compares the adjacent elements and swaps them if they are in the wrong order. This process continues until no swaps are needed, indicating that the list has been sorted.

*Image
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure

Bubble Sort Algorithm in Java

Let’s see how the bubble sorting algorithm works.

 

  • Run the two loops that are nested in one another.
  • The outer loop will run from i=0 to i< n-1, where n is the number of elements listed.
  • There is one more loop, which is run on the inner loop j=0 to j< n -i -1. It is because, after each iteration of the outer loop, one another element at the end (or at the start if the order is decreasing order) will be in its right place, so we can leave it as is. Then, we will check if the arr[j] > arr[j+1]. If it’s true, then we will swap places at these elements. If the condition is false, we will continue with the next iteration.  This process will be repeated till the conditions of the loop are not satisfied.
  • This process will be repeated till the conditions of the loop are not satisfied.

 

For Decreasing, we have to change this thing in our bubble sort algorithm.

 

  • This inner loop will run from j = i to j< n-1.
  • We will compare the elements as arr[j] < arr[j+1]

 

The following program demonstrates the Bubble Sort in Java:

 

Program

class Main{ public static void bubbleSort(int []arr){ int n = arr.length ; boolean swapped ; for(int i =0 ;i< n-1;i++){ swapped = false ; }   for(int j = 0;j< n-1 -i;j++){ if(arr[j] > arr[j+1]){ int temp  = arr[j] ; arr[j] = arr[j+1] ; arr[j+1] = temp ; swapped = true ; } } }   public static void display(int []arr){ for(int num: arr){ System.out.println(num+" "); } } public static void main(String args[]){ int [] arr = {64,32,25,12,33,11,90} ; System.out.println("Unsorted Array"); display(arr);   bubbleSort(arr);   System.out.println("Sorted Array"); display(arr); } }

Output

Unsorted Array 64 32 25 12 33 11 90 Sorted Array 11 12 25 32 33 64 90

Complexity Analysis of Bubble Sort:

 

Time Complexity: O(N2), where N is the number of the items in the list

Auxiliary Space: O(N)

Working of Bubble Sort in Java

This section explains how the Bubble Sort Algorithm works.  Let’s sort an unsorted array using the Bubble Sort Array.

 

Let’s take the example of an array.

 

13 12 26 35 10

 

First Iteration

 

In the first iteration, we will compare the initial two elements to check whether the first element is greater or less in an array.

 

13 32 26 35 10

 

In this array, 32 is greater than the first element of the array, which is 13. So it is already sorted. We don’t need to sort them.

 

13 32 26 35 10

 

In this array, 26 is smaller than 32. Then, we will swap. After swapping, the new array will look like this.

 

13 26 32 35 19

 

Now, we compare 32 and 35.

 

13 26 32 35 10

 

Now, 35 is greater than 32. So, no swapping is required in this new sorted array. Let’s compare it to between 35 and 10..

 

13 26 32 35 10

 

Second Iteration

 

The same process will be followed in the second phase of iterations. 

 

13 26 32 10 35

 

13 26 32 10 32

 

13 26 32 10 35

 

Here, we will see that ten is smaller than 32. So, swapping will be performed. After swapping, the array will be.

 

13 26 10 32 35

 

13 26 10 32 35

 

Let’s move to the third iteration in the loop.

 

Third Iteration

 

The same process will be followed for the third iteration in this section.

 

13 26 10 32 35

 

13 26 10 32 35

 

10 is smaller than 26, so I will swap them. After swapping, the array will look like this.

 

13 10 26 32 35

 

13 10 26 32 35

 

Now, let’s move to the fourth iteration.

Fourth Iteration

 

In the fourth iteration, the array will look like this.

10 13 26 32 35

 

Here, we don’t need to swap any element. This array is already sorted.

Implementation of Bubble Sort in Java

In this section, we will implement the bubble sort algorithm in Java, which sorts a list.

 

The following program demonstrates Bubble Sort in Java:

 

Program

public class BubbleSort { public static void bubbleSort(int[] arr) { int n = arr.length; for (int i = 0; i < n - 1; i++) { for (int j = 0; j < n - i - 1; j++) { if (arr[j] > arr[j + 1]) { int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } }   public static void main(String[] args) { int[] arr = {64, 34, 25, 12, 22, 11, 90}; System.out.println("Before Sorted") ; for(int num :arr){ System.out.print(num+" ") ; } System.out.println(); bubbleSort(arr); System.out.println("Sorted array:"); for (int num : arr) { System.out.print(num + " "); } } }

Output

Before Sorted 64 34 25 12 22 11 90 Sorted array: 11 12 22 25 34 64 90

Advantages of Bubble Sort in Java

The advantages of Bubble Sort in Java without number formatting:

 

  • Simplicity: The Bubble sort algorithm is easy to understand and implement, making it accessible for beginners.

 

  • No Extra Memory Usage: The bubble sort operates in place, requiring no additional memory beyond the original array, leading to a space complexity of O(1).

 

  • Stable Sorting: It maintains the relative order of equal elements, which can be important in applications where the order matters.

 

  • Education Value: Bubble sort is the foundational algorithm for learning basic sorting concepts and understanding algorithm design.

Disadvantages of Bubble Sort in Java

The bubble sort algorithm also has some disadvantages:

 

  • High Number of Comparisons: The algorithm performs many comparisons and swaps, which can lead to significant overhead and slower performance as the dataset grows.

 

  • Not Cache-Friendly: The bubble sort may not efficiently utilize CPU cache due to its repeated access patterns, which can further hinder performance.

 

  • Increased Development Time: Developers may need to spend additional time implementing and optimizing bubble sort for specific use cases, even though better alternatives exist.

 

Also Read: Call by Value and Call by Reference in Java

Conclusion

It is a very simple sorting algorithm that introduces the concept of sorting and algorithm design. It is a comparison-based algorithm design. Being a comparison-based algorithm, comparison and swap of adjacent elements make it understandable, which is one of the many reasons it is often used for didactic purposes. It is a very valuable sorting algorithm for understanding the other algorithmic principles. It is essential to recognize its constraints and consider more efficient alternatives for practical use. Understanding bubble sort sets the groundwork for exploring more complex algorithms.

FAQs
Yes, Bubble Sort can be implemented for linked lists, but it is generally inefficient. Other algorithms like Merge Sort are preferred for linked lists.
An optimized version of Bubble Sort can be considered adaptive because it can finish early if the array becomes sorted before completing all passes.
Yes, the bubble sort algorithm can handle large integers if they fit within the data type used in the implementations (eg, int, long).

Updated on September 20, 2024

Link
left dot patternright dot pattern

Programs tailored for your success

Popular

Management

Data Science

Finance

Technology

Future Tech

Upskill with expert articles

View all
Hero Vired logo
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.
Blogs
Reviews
Events
In the News
About Us
Contact us
Learning Hub
18003093939     ·     hello@herovired.com     ·    Whatsapp
Privacy policy and Terms of use

|

Sitemap

© 2024 Hero Vired. All rights reserved