method to order an array using bubble sort in python

Here's a sample implementation of Bubble Sort in Python:

main.py
def bubble_sort(arr):
    n = len(arr)
    # Traverse through all array elements
    for i in range(n):
        # Last i elements are already in place
        for j in range(0, n-i-1):
            # traverse the array from 0 to n-i-1
            # Swap if the element found is greater
            # than the next element
            if arr[j] > arr[j+1] :
                arr[j], arr[j+1] = arr[j+1], arr[j]
    return arr
423 chars
13 lines

This implementation takes an array arr as input and sorts it using the Bubble Sort algorithm. The inner loop iterates over the array from 0 to n-i-1 and swaps adjacent elements if the left element is greater than the right element. The outer loop iterates over the array n times, where n is the length of the array.

Here's an example of how to use this function:

main.py
arr = [64, 34, 25, 12, 22, 11, 90]
sorted_arr = bubble_sort(arr)
print(sorted_arr) # Output: [11, 12, 22, 25, 34, 64, 90]
122 chars
4 lines

This will output the sorted array.

gistlibby LogSnag