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.
How Bubble Sort Works
- Start from the beginning of the list.
- Compare the first two elements.
- If the first element is greater than the second element, swap them.
- Move to the next pair of elements and repeat the process.
- Continue this way until you reach the end of the list.
- Once you reach the end, start again from the beginning.
- Repeat the process until no swaps are needed, which means the list is sorted.
Example
Here's a simple example of bubble sort in action:
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
return arr
# Test the function
arr = [64, 34, 25, 12, 22, 11, 90]
sorted_arr = bubble_sort(arr)
print("Sorted array is:", sorted_arr)
Performance
Bubble sort has a time complexity of O(n^2), making it inefficient on large lists. However, it can be useful for small lists or lists that are nearly sorted.
Visual Representation
Bubble Sort Animation
For more information on sorting algorithms, you can visit our Sorting Algorithms page.