Mastering Java: A Step-by-Step Guide to Implementing Bubble Sort Algorithm
Are you ready to take your Java skills to the next level? Let’s dive into the world of sorting algorithms and explore the popular Bubble Sort technique.
Understanding the Basics
Before we begin, make sure you have a solid grasp of Java fundamentals, including methods, for loops, and arrays. These concepts are crucial in implementing the Bubble Sort algorithm.
The Bubble Sort Algorithm: A Closer Look
So, how does Bubble Sort work? Essentially, it’s a simple sorting technique that repeatedly steps through the list, compares adjacent elements, and swaps them if they’re in the wrong order. This process continues until the list is sorted.
Java Program to Implement Bubble Sort Algorithm
Now, let’s get hands-on and create a Java program that implements the Bubble Sort algorithm. Our program will take user input to decide whether to sort the array in ascending or descending order.
“`java
// 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 our 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!