Junior — Middle
Can you explain how the bubble sort algorithm works?
sobes.tech AI
Answer from AI
The bubble sort algorithm works on the principle of multiple passes through the array, during which adjacent elements are compared and swapped if they are in the wrong order. As a result, after each pass, the largest (or smallest) element 'bubbles up' to the end of the array, like a bubble in water.
Example in Java:
public void bubbleSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
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;
}
}
}
}
This algorithm is simple but inefficient for large arrays, as it has a complexity of O(n²).