Bubble Sort in Python

Bubble Sort in Python

Bubble sort is an algorithm for sorting an array by repeatedly swapping adjacent elements if they are in the wrong order. It works by iterating through the array and comparing adjacent elements, and then swapping them if they are in the wrong order. This process is repeated until the array is sorted.

Here is an example of how you might implement bubble sort in Python:

def bubble_sort(array):
    n = len(array)
    for i in range(n - 1):
        for j in range(n - i - 1):
            if array[j] > array[j + 1]:
                array[j], array[j + 1] = array[j + 1], array[j]
    return array

array = [4, 3, 2, 1]
sorted_array = bubble_sort(array)
print(sorted_array) # Outputs [1, 2, 3, 4]

In this example, the bubble_sort function takes an array as input and returns the sorted array. It uses two nested for loops to iterate through the array and compare adjacent elements, and then swaps them if they are in the wrong order. The inner loop iterates through the array from the beginning to the end, and the outer loop iterates from the end to the beginning, reducing the number of iterations each time.

I hope this helps! Let me know if you have any other questions.


 

Post a Comment

0 Comments