Skip to content

Instantly share code, notes, and snippets.

@maycuatroi1
Last active October 26, 2025 22:49
Show Gist options
  • Select an option

  • Save maycuatroi1/90ae5f003bcad26fa8a9fae243fac099 to your computer and use it in GitHub Desktop.

Select an option

Save maycuatroi1/90ae5f003bcad26fa8a9fae243fac099 to your computer and use it in GitHub Desktop.
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