A simple sorting algorithm with O(n²) complexity.
Bubble Sort is a straightforward sorting algorithm that repeatedly compares adjacent elements and swaps them if they are in the wrong order. Although its time complexity is \( O(n^2) \), it is easy to implement and serves as an excellent way to learn sorting algorithms.
def bubble_sort(arr):
n = len(arr)
for i in range(n - 1):
swapped = False
for j in range(n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
swapped = True
if not swapped:
break
return arr
# Example Usage
unsorted_list = [64, 34, 25, 12, 22, 11, 90]
print("Unsorted List:", unsorted_list)
sorted_list = bubble_sort(unsorted_list)
print("Sorted List:", sorted_list)
Unsorted List: [64, 34, 25, 12, 22, 11, 90] Sorted List: [11, 12, 22, 25, 34, 64, 90]