Understanding Bubble Sort in Detail
1. Utilizing Nested For Loops
Bubble Sort employs two nested loops. The outer loop determines the number of passes through the array, while the inner loop compares each element of the array.
Utilizing Nested For Loops
for i in range(n):
for j in range(0, n-i-1):
2. Element Comparison and Swap
Within the inner loop, adjacent elements are compared and swapped if necessary.
Element Comparison and Swap Example
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
Bubble Sort Time Complexity
-
Worst-case Time Complexity
: O(n^2)- This occurs when the array is sorted in reverse order compared to the desired sort. In this case, every element must be compared with every other element. If the size of the array is n, it requires (n x n) comparisons.
-
Average Time Complexity
: O(n^2)- Even in typical situations where array elements are randomly arranged, approximately (n x n) comparisons are needed.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.