Created
July 23, 2024 23:25
-
-
Save gazolla/23e2370e8827a995955c6d07c9d21f45 to your computer and use it in GitHub Desktop.
Bubble sort algorithm in Java
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 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