Bubble Sort
Anjana Silva
Remote Leadership & Web Dev Expert ?? | Helping Teams Thrive ?? | Follow for Practical Tips ?? | Cricket Enthusiast ??
Bubble sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. The pass through the list is repeated until the list is sorted.
When to use bubble sort:
?Bubble sort is easy to understand and implement, making it suitable for small datasets or educational purposes.
? It is also useful when the input list is mostly sorted or nearly sorted, as it performs relatively well in this case.
When not to use bubble sort:
?Bubble sort has a time complexity of O(n^2), making it inefficient for large datasets. For large datasets, other more efficient sorting algorithms like quicksort, mergesort, or heapsort should be used.
?It is not suitable for sorting large arrays or lists due to its poor performance compared to other sorting algorithms.
Bubble sort example in Python,
def bubble_sort(arr):
n = len(arr)
for i in range(n):
print('i = ' + str(i))
for j in range(0, n-i-1):
print('j = ' + str(j))
# Traverse the array from 0 to n-i-1
# Swap if the element found is greater than the next element
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
I hope you enjoyed this post. Thank you.