DEV Community

loading...

Bubble Sort in Python

annlin profile image ann lin ・1 min read

Become a Software Engineer -> Pass Technical Interview -> Be darn good at Data Structure and Algorithms -> Starting with Sorting Algorithms -> 1. Bubble Sort

Bubble Sort (Decreasing Order)

def bubblesort(array):
    # we minus 1 because we are always comparing the current value with the next value
    lengthOfArray = len(array) - 1
    # numbe of rounds will be the total length - 1, for array with length 5, we will do 4 rounds: 0 and 1, 1 and 2, 2 and 3, 3 and 4.
    for i in range(lengthOfArray):
        # at each round, we compare the current j with the next value
        for j in range(lengthOfArray - i):
            # only swap their positions if left value < right value as we aim to move all the small values to the back
            if array[j] < array[j + 1]:
                array[j], array[j + 1] = array[j + 1], array[j]

    return array


array = [2, 1, 5, 4, 3]
print bubblesort(array)

Discussion (6)

pic
Editor guide
Collapse
chenge profile image
chenge

The video is funny, good idea. Numbers are really boring.

Collapse
annlin profile image
ann lin Author

aww thanks, took the chance to showcase my favourite people too :)

Collapse
chenge profile image
chenge

I want to see quick sort. When will you publish it?

Thread Thread
annlin profile image
ann lin Author • Edited

Your wish is my command. Coming up soon :)

Thread Thread
chenge profile image
chenge

Thanks for caring, expecting..., :)

Collapse
sekr4 profile image