Skip to content

Instantly share code, notes, and snippets.

@gazolla
Created July 23, 2024 23:25
Show Gist options
  • Save gazolla/23e2370e8827a995955c6d07c9d21f45 to your computer and use it in GitHub Desktop.
Save gazolla/23e2370e8827a995955c6d07c9d21f45 to your computer and use it in GitHub Desktop.
Bubble sort algorithm in Java
public class App {
public static void main(String[] args) {
int[] array = {5,9,1,8,2,7,3,6,4};
System.out.println("original " + array);
bubbleSort(array);
System.out.println("sorted " + array);
}
private static void bubbleSort(int[] array) {
boolean swapped;
int n = array.length;
for (int i = 0; i < n; i++) {
swapped = false;
for (int j = 0; j < n -1 -i; j++) {
if (array[j] > array[j +1]) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
swapped = true;
}
}
if(!swapped) break;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment