Last active
October 26, 2025 22:49
-
-
Save maycuatroi1/90ae5f003bcad26fa8a9fae243fac099 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public class BubbleSort { | |
| public static void bubbleSort(int[] arr) { | |
| int n = arr.length; | |
| boolean swapped; | |
| for (int i = 0; i < n - 1; i++) { | |
| swapped = false; | |
| for (int j = 0; j < n - i - 1; j++) { | |
| if (arr[j] > arr[j + 1]) { | |
| int temp = arr[j]; | |
| arr[j] = arr[j + 1]; | |
| arr[j + 1] = temp; | |
| swapped = true; | |
| } | |
| } | |
| // If no swaps were made, array is already sorted | |
| if (!swapped) { | |
| break; | |
| } | |
| } | |
| } | |
| public static void printArray(int[] arr) { | |
| for (int i = 0; i < arr.length; i++) { | |
| System.out.print(arr[i] + " "); | |
| } | |
| System.out.println(); | |
| } | |
| public static void main(String[] args) { | |
| int[] arr = {64, 25, 12, 22, 11}; | |
| System.out.println("Original array:"); | |
| printArray(arr); | |
| bubbleSort(arr); | |
| System.out.println("Sorted array:"); | |
| printArray(arr); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment