Data Structures and Algorithms: How to Sort a List Using Bubble Sort in Python

python 301 algorithms bubble sort

Bubble sort is a simple and common sorting algorithm that works by repeatedly swapping adjacent elements in a list that are out of order. It compares each pair of elements and moves the larger one to the right until the list is sorted. You can see an example of bubble sort in Python in this web search result.

Bubble sort is easy to implement and understand, but it is not very efficient or fast. It has a time complexity of O(n^2), which means that it takes quadratic time to sort a list of n elements. It also requires extra space to store the swapped elements. Therefore, bubble sort is not suitable for large or complex data sets.

def bubble_sort(arr):
    n = len(arr)

    for i in range(n): # Traverse through all elements
        for j in range(0, n-i-1):
            if arr[j] > arr[j+1]:
                arr[j], arr[j+1] = arr[j+1], arr[j] # Swap

my_list = [64, 34, 25, 12, 22, 11, 90]
print("Original List:", my_list)

bubble_sort(my_list)

print("Sorted List:", my_list) # Sorted List: [11, 12, 22, 25, 34, 64, 90]

This demonstrates the basic concept of Bubble Sort. The algorithm iterates through the list, compares adjacent elements, and swaps them if they are in the wrong order. This process is repeated until the entire list is sorted. Note that Bubble Sort is not the most efficient sorting algorithm, especially for large datasets, but it serves as a good educational example due to its simplicity.

Other example

def bubble_sort(data):
    # Traverse the items
    for i in range(len(data) - 1):
        for j in range(len(data) - i - 1):
            if data[j] > data[j + 1]:
                # swap the elements
                data[j], data[j + 1] = data[j + 1], data[j]

# Example usage
data = [4, 2, 5, 1, 3]
bubble_sort(data)
print(data) # Output: [1, 2, 3, 4, 5]

Here are some of the key points to remember about Bubble Sort:

  • It is a simple algorithm that is easy to understand and implement.
  • It is efficient for small datasets but inefficient for large datasets.
  • It has a time complexity of O(n^2), where n is the length of the list.
  • It is not a stable sorting algorithm, meaning that the relative order of equal elements may not be preserved.

Quiz

Related posts

Leave a Comment