Bubble Sort—Python

Many computer science students are expected to perform sorting. Here is an example of doing a bubble sort in Python.

def bubble_sort(array):
    # Grab the length of the array
    n = len(array)

    # Iterate through array from 0 to n
    for i in range(len(array)):

        # Iterate through array from 1 to n - i
        for j in range(1, n - i):

            # Now check if the element at array[j - 1] is larger than array[j]
            if array[j - 1] > array[j]:
                # Perform a swap of the elements
                temp = array[j - 1]
                array[j - 1] = array[j]
                array[j] = temp

if __name__ == '__main__':
    unsorted = [10, 5, 2, 3, 1]
    print('Unsorted list is: ', unsorted)

    print('Sorted list is now: ', unsorted)

One thought on “Bubble Sort—Python”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: