Bubble Sort Implementation in Java - A Detailed Guide of Character Sorting

Data Structure Sorting (Article) Sorting (Program)

91

Sorting algorithms play a crucial role in computer science, helping to organize data efficiently. One of the simplest sorting algorithms is Bubble Sort. It repeatedly compares adjacent elements and swaps them if they are in the wrong order. Although not the most efficient algorithm, Bubble Sort is an excellent way to understand the fundamentals of sorting.

In this blog post, we'll dive deep into Bubble Sort, understand its working with an example, analyze its time complexity, and implement it in Java.

Given Input:

Input Array: ['d', 'a', 'c', 'b']

Expected Output:

Sorted Array: ['a', 'b', 'c', 'd']

Program:

import java.util.*;

public class Charsort {
    public static void bubbleSort(char[] array) {
        int num = array.length;
        char temp;

        for (int i = 0; i < num - 1; i++) {  // Loop runs num-1 times
            for (int j = 0; j < num - i - 1; j++) {  // Inner loop reduces after each pass
                if (array[j] > array[j + 1]) {  // Swap if elements are in wrong order
                    temp = array[j];
                    array[j] = array[j + 1];
                    array[j + 1] = temp;
                }
            }
        }
    }

    public static void main(String[] args) {
        char array[] = new char[10];
        Scanner sc = new Scanner(System.in);

        System.out.println("Enter 10 characters:");
        for (int i = 0; i < 10; i++) {
            array[i] = sc.next().charAt(0);  // Use sc.next() to avoid newline issues
        }

        System.out.println("Array Before Bubble Sort: " + Arrays.toString(array));
        bubbleSort(array);
        System.out.println("Array After Bubble Sort: " + Arrays.toString(array));
        
        sc.close();  // Close Scanner to avoid resource leak
    }
}

Output:

Sorted Array: ['a', 'b', 'c', 'd']

Explanation:

What is Bubble Sort?

Bubble Sort is a comparison-based sorting algorithm that works by repeatedly swapping adjacent elements if they are in the wrong order. The process continues until the entire array is sorted.

How Bubble Sort Works (Step-by-Step Example)

Let's take an example to understand the process:

Input Array: ['d', 'a', 'c', 'b']

1st Pass:

  • Compare 'd' and 'a' → Swap → ['a', 'd', 'c', 'b']

  • Compare 'd' and 'c' → Swap → ['a', 'c', 'd', 'b']

  • Compare 'd' and 'b' → Swap → ['a', 'c', 'b', 'd']

2nd Pass:

  • Compare 'a' and 'c' → No Swap

  • Compare 'c' and 'b' → Swap → ['a', 'b', 'c', 'd']

  • 'd' is already in place, so we stop early.

Sorted Array: ['a', 'b', 'c', 'd']


Java Implementation of Bubble Sort

Let's now implement the Bubble Sort Algorithm in Java:


Understanding the Code

  1. User Input: The user enters 10 characters, which are stored in an array.

  2. Bubble Sort Function:

    • The outer loop (i) iterates n-1 times.

    • The inner loop (j) swaps adjacent elements if they are in the wrong order.

    • The largest element moves to the rightmost position after each pass.

  3. Display Results: The sorted array is printed after sorting.


Time Complexity Analysis

Best Case (Already Sorted Array):

  • The loop runs O(n), as no swaps are required.

  • Time Complexity: O(n)

Worst & Average Case (Random Order):

  • The loop runs O(n^2), performing unnecessary comparisons.

  • Time Complexity: O(n²)


Advantages and Disadvantages of Bubble Sort

? Advantages:

  • Simple and easy to implement.

  • Works well for small datasets.

? Disadvantages:

  • Inefficient for large datasets.

  • Requires O(n²) comparisons in the worst case.


Conclusion

Bubble Sort is a fundamental sorting algorithm that helps understand basic sorting mechanisms. While it's not suitable for large datasets due to its inefficiency, it is an excellent starting point for learning sorting techniques.

Would you like to explore more efficient sorting algorithms like Quick Sort, Merge Sort, or Heap Sort? Let us know in the comments!

Happy Coding! ?

 


This Particular section is dedicated to Programs only. If you want learn more about Data Structure. Then you can visit below links to get more depth on this subject.