Mastering Java: A Step-by-Step Guide to Implementing Bubble Sort Algorithm

Understanding the Basics

Before diving into the Bubble Sort algorithm, ensure you have a solid grasp of Java fundamentals, including:

  • Methods
  • For loops
  • Arrays

These concepts are crucial in implementing the Bubble Sort algorithm.

The Bubble Sort Algorithm: A Closer Look

The Bubble Sort algorithm is a simple sorting technique that:

  • Repeatedly steps through the list
  • Compares adjacent elements
  • Swaps them if they’re in the wrong order

This process continues until the list is sorted.

Java Program to Implement Bubble Sort Algorithm

Create a Java program that implements the Bubble Sort algorithm. The program will take user input to decide whether to sort the array in ascending or descending order.


// Java program to implement Bubble Sort algorithm
import java.util.Scanner;

public class BubbleSort {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.print("Enter 1 for ascending order or 2 for descending order: ");
    int choice = scanner.nextInt();

    int[] array = {5, 3, 8, 4, 2};
    bubbleSort(array, choice);
    printArray(array);
  }

  public static void bubbleSort(int[] array, int choice) {
    int n = array.length;
    for (int i = 0; i < n - 1; i++) {
      for (int j = 0; j < n - i - 1; j++) {
        if ((choice == 1 && array[j] > array[j + 1]) || (choice == 2 && array[j] < array[j + 1])) {
          // Swap array[j] and array[j + 1]
          int temp = array[j];
          array[j] = array[j + 1];
          array[j + 1] = temp;
        }
      }
    }
  }

  public static void printArray(int[] array) {
    for (int i = 0; i < array.length; i++) {
      System.out.print(array[i] + " ");
    }
    System.out.println();
  }
}

Output and Explanation

Let’s see our program in action:

If we enter 1 as input, the program sorts the array in ascending order. On the other hand, if we enter 2, the program sorts the array in descending order.

Ascending Order (Input: 1)

The output will be: 2 3 4 5 8

Descending Order (Input: 2)

The output will be: 8 5 4 3 2

Take Your Learning to the Next Level

Want to learn more about the Bubble Sort algorithm and its applications? Explore resources and dive deeper into the world of sorting algorithms. With practice and persistence, you’ll become a master of Java programming in no time!

Leave a Reply