Bubble Sort
Bubble Sort
Where:-
T(n) represents the time complexity (number of operations)- n represents the size
of the input array (number of elements)- O(n^2) represents the quadratic growth
rate of the algorithm's complexity
This formula indicates that the number of operations (comparisons and swaps)
grows quadratically with the size of the input array.
To break it down further:- In the worst-case scenario (e.g., reverse-sorted array),
Bubble Sort makes:
- n-1 comparisons in the first pass
- n-2 comparisons in the second pass
- - ...
- - 1 comparison in the last pass-
This results in a total of (n-1) + (n-2) + ... + 1 = n*(n-1)/2 comparisons-
Since the algorithm also makes a similar number of swaps, the total time
complexity is O(n^2)
Keep in mind that this is an upper bound, and the actual number of operations
may be less in specific cases (e.g., nearly sorted arrays). However, O(n^2)
represents the worst-case scenario and provides a simple and informative estimate
of Bubble Sort's complexity.
Time and Space Complexity Analysis of
Bubble Sort
The time complexity of Bubble Sort is O(n^2) in the worst-case
scenario and the space complexity of Bubble sort is O(1).
Bubble Sort only needs a constant amount of additional space during
the sorting process.
Complexity Type Complexity
Time Complexity Best: O(n)
Average: O(n^2)
Worst: O(n^2)
Space Complexity Worst: O(1)
In worst case,
Total number of swaps = Total number of comparison
Total number of comparison (Worst case) = N(N-1)/2
Total number of swaps (Worst case) = N(N-1)/2
So worst case time complexity is O(N2) as N2 is the highest order
term.
Average Case Time Complexity Analysis of Bubble Sort: O(N2)
The number of comparisons is constant in Bubble Sort. So in average
case, there are O(N2) comparisons. This is because irrespective of the
arrangement of elements, the number of comparisons C(N) is same.
Space Complexity Analysis of Bubble Sort:
The space complexity of Bubble Sort is O(1). This means that the
amount of extra space (memory) required by the algorithm remains
constant regardless of the size of the input array being sorted. Bubble
Sort only needs a constant amount of additional space to store temporary
variables.
Therefore, the space complexity of Bubble Sort is considered to be very
efficient as it does not depend on the input size and does not require
additional space proportional to the input size.
Advantages of Bubble Sort:
•Bubble sort is easy to understand and implement.
•It does not require any additional memory space.
•It is a stable sorting algorithm, meaning that elements with the same
key value maintain their relative order in the sorted output.