Java Code
// Java program for Bubble Sort
public class BubbleSort {
public static void main(String[] args) {
int[] arr = {5, 1, 4, 2, 8};
// Outer loop for each pass
for (int i = 0; i < arr.length - 1; i++) {
// Inner loop for pairwise comparisons
for (int j = 0; j < arr.length - i - 1; j++) {
// Swap if elements are in wrong order
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
// Print sorted array
System.out.print("Sorted array: ");
for (int num : arr) {
System.out.print(num + " ");
}
}
}
Output
Sorted array: 1 2 4 5 8