Java Online Compiler
Example: Sort Array using Bubble Sort in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Sort Array using Bubble Sort public class Main { public static void main(String[] args) { // Step 1: Declare and initialize an unsorted integer array. int[] numbers = {5, 2, 8, 1, 9, 4}; System.out.print("Original array: "); printArray(numbers); // Step 2: Implement Bubble Sort logic. // Outer loop for passes. A pass ensures at least one element bubbles to its correct place. for (int i = 0; i < numbers.length - 1; i++) { // Inner loop for comparisons and swaps within each pass. // (numbers.length - 1 - i) optimizes by not re-checking elements already at their final position. for (int j = 0; j < numbers.length - 1 - i; j++) { // Compare adjacent elements if (numbers[j] > numbers[j + 1]) { // Swap if the element found is greater than the next element int temp = numbers[j]; numbers[j] = numbers[j + 1]; numbers[j + 1] = temp; } } } // Step 3: Print the sorted array. System.out.print("Sorted array (Bubble Sort): "); printArray(numbers); } // Helper method to print the array elements public static void printArray(int[] arr) { for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + (i < arr.length - 1 ? ", " : "")); } System.out.println(); } }
Output
Clear
ADVERTISEMENTS