Python
Python

 

 

The Bubble Sort algorithm 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 process is repeated until the list is sorted.

Python Implementation

def bubble_sort(arr):
    """
    Sorts a list using the Bubble Sort algorithm.

    Parameters:
    arr (list): The list of elements to be sorted.

    Returns:
    list: The sorted list.
    """
    n = len(arr)
    for i in range(n):
        # Track if a swap has occurred
        swapped = False
        for j in range(0, n-i-1):
            # Compare adjacent elements
            if arr[j] > arr[j+1]:
                # Swap if they are in the wrong order
                arr[j], arr[j+1] = arr[j+1], arr[j]
                swapped = True
        # If no two elements were swapped in the inner loop, break
        if not swapped:
            break
    return arr

# Example usage
if __name__ == "__main__":
    sample_list = [64, 34, 25, 12, 22, 11, 90]
    sorted_list = bubble_sort(sample_list)
    print("Sorted list:", sorted_list)

Program Structure Explanation

  • Function Definition: The function bubble_sort(arr) is defined to take a list arr as its parameter.
  • Length Calculation: The length of the list is calculated using len(arr) and stored in the variable n.
  • Outer Loop: The outer loop runs n times. It ensures that we pass through the list enough times to sort it.
  • Swapping Flag: A boolean variable swapped is initialized to track whether any swaps were made during the inner loop.
  • Inner Loop: The inner loop compares adjacent elements. If the element at index j is greater than the one at index j+1, they are swapped.
  • Early Termination: If no swaps occurred during the inner loop, the list is already sorted, and the outer loop can break early.
  • Return Value: The function returns the sorted list.

Example Usage

The program includes an example usage section. A sample list is provided, and the sorted result is printed to the console.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)