Bubble Sort
Bubble Sort — compares adjacent elements and swaps them if they are in the wrong order.
public static void bubbleSort(int[] array) {
int n = array.length;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (array[j] > array[j + 1]) {
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
}
int[] numbers = {5, 3, 8, 1, 2};
bubbleSort(numbers);
System.out.println(Arrays.toString(numbers)); // Outputs: [1, 2, 3, 5, 8]
Semantic portal