Bubble Sort Program in Java for Class 10 ICSE
Bubble Sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order. The pass through the list is repeated until the list is sorted. This algorithm is named "bubble sort" because smaller elements "bubble" to the top of the list like bubbles in a glass of water.
Here's a Java program demonstrating the Bubble Sort algorithm:
import java.util.Arrays;
public class BubbleSort {
public static void main(String[] args) {
// Unsorted array
int[] arr = {64, 34, 25, 12, 22, 11, 90};
// Print the unsorted array
System.out.println("Unsorted Array:");
System.out.println(Arrays.toString(arr));
// Implement Bubble Sort
bubbleSort(arr);
// Print the sorted array
System.out.println("\nSorted Array:");
System.out.println(Arrays.toString(arr));
}
// Function to perform bubble sort
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]) {
// Swap elements if in wrong order
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
}
Explanation:
-
Initialization:
- An unsorted array
arr
is created. bubbleSort
function is called to sort the array.
- An unsorted array
-
Outer Loop:
- The outer loop iterates
n-1
times, wheren
is the length of the array. - Each iteration places the largest element in its correct position.
- The outer loop iterates
-
Inner Loop:
- The inner loop iterates through the unsorted portion of the array, comparing adjacent elements.
- If the elements are in the wrong order, they are swapped.
-
Swapping:
- A temporary variable
temp
is used to store the value of the first element while swapping.
- A temporary variable
Output:
Unsorted Array:
[64, 34, 25, 12, 22, 11, 90]
Sorted Array:
[11, 12, 22, 25, 34, 64, 90]
Important Notes:
- Bubble Sort is an in-place sorting algorithm, meaning it modifies the original array directly without creating a new one.
- The time complexity of Bubble Sort is O(n^2), which makes it inefficient for large datasets.
- This algorithm is relatively easy to understand and implement, making it suitable for beginners learning about sorting algorithms.
Further Learning:
- Explore other sorting algorithms like Insertion Sort, Selection Sort, Merge Sort, and Quick Sort.
- Understand the time complexity and space complexity of different sorting algorithms.
- Practice implementing these algorithms in Java and other programming languages.