Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. The pass through the list is repeated until the list is sorted.
How Bubble Sort Works:
- Starting from the first index, compare the first and the second elements.
- If the first element is greater than the second element, they are swapped.
- Now, compare the second and the third element. Swap them if they are not in order.
- The above process goes on until the last element.
- The same process goes on for the remaining iterations.
Complexity Analysis:
- Time Complexity: O(n²) in the worst and average case, O(n) in the best case (when the array is already sorted).
- Space Complexity: O(1) (in-place sorting).
Characteristics:
- Bubble Sort is stable.
- It is an in-place sorting algorithm.
- Not suitable for large datasets due to its O(n²) time complexity.
- The graph describing the Bubble Sort time complexity looks like this:
