Monday, 6 November 2023

Write a python script to implement bubble sort using list

 

Write a python script to implement bubble sort using list 

def bubble_sort(arr):

    n = len(arr)

 

    for i in range(n):

        swapped = False

 

        for j in range(0, n - i - 1):

            if arr[j] > arr[j + 1]:

                # Swap the elements 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 inner loop, the array is already sorted

        if not swapped:

            break

 

# Example usage:

arr = [64, 34, 25, 12, 22, 11, 90]

print("Original array:", arr)

 

bubble_sort(arr)

 

print("Sorted array:", arr)