Introduction
Bubble Sort is one of the simplest sorting techniques in Java. It is commonly asked in BCA exams, practicals, and viva to test understanding of loops and arrays.
In this article, you will learn:
What is Bubble Sort
How Bubble Sort works
Bubble Sort program in Java
Step-by-step dry run
❓ What Is Bubble Sort?
Bubble Sort is a sorting algorithm that repeatedly compares adjacent elements and swaps them if they are in the wrong order.
π Larger elements “bubble up” to the end of the array, just like air bubbles rise in water.
π§ How Bubble Sort Works
Compare first and second element
Swap if first > second
Move to next pair
Repeat passes until array is sorted
π§© Algorithm for Bubble Sort
Start
Read array elements
Repeat for passes from 0 to n-1
Compare adjacent elements
Swap if they are in wrong order
Print sorted array
End
π» Bubble Sort Program in Java
import java.util.Scanner;
public class BubbleSort {
public static void main(String[] args) {
int n, temp;
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of elements: ");
n = sc.nextInt();
int[] arr = new int[n];
System.out.println("Enter array elements:");
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
// Bubble Sort Logic
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
System.out.println("Sorted Array:");
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
}
}
π§ͺ Dry Run
Input
Array = {5, 3, 1}
Pass 1
Compare 5 & 3 → swap → {3, 5, 1}
Compare 5 & 1 → swap → {3, 1, 5}
Pass 2
Compare 3 & 1 → swap → {1, 3, 5}
Final Sorted Array
1 3 5
π₯️ Output
Enter number of elements: 3
Enter array elements:
5 3 1
Sorted Array:
1 3 5
π Important Points for Exams
Bubble Sort uses nested loops
Time Complexity:
Worst case: O(n²)
Best case: O(n) (optimized version)
Space Complexity: O(1)
Easy but not efficient for large data
π Advantages & Disadvantages
✅ Advantages
Easy to understand
Simple implementation
Good for small data
❌ Disadvantages
Very slow for large arrays
Not used in real-world applications
Comments
Post a Comment