Implement the Bubble Sort algorithm. Repeatedly step through the list, compare adjacent elements, and swap them if they are in the wrong order. The pass through the list is repeated until the list is sorted.
In each pass, compare adjacent pairs and swap if needed. The largest unsorted element "bubbles up" to its correct position. Optimize by stopping early if no swaps occur in a pass.
- Outer loop runs n-1 times (n = array length).
- Inner loop compares arr[j] and arr[j+1] for j from 0 to n-i-2.
- If arr[j] > arr[j+1], swap them.
- Use a swapped flag to break early if the array is already sorted.
- Time Complexity: O(N^2) worst/average, O(N) best (already sorted)
- Space Complexity: O(1) in-place