6
\$\begingroup\$

I have implemented a Bubble Sort. It works well. But if you think something needs to be improved, say it. This code was tested in Python 3.7.4.

def bubble_sort(nums):

    for i in range(len(nums)-1):
        for j in range(0,len(nums)-1-i,1):
            if nums[j] > nums[j+1]:
                swap(nums, j, j+1)

    return nums

def swap(nums, i, j):
    temp = nums[i]
    nums[i] = nums[j]
    nums[j] = temp

if __name__ == "__main__":

   a = [0,0,0,-1,-0,1,2,3,2,1]
   print(bubble_sort(a))
\$\endgroup\$
1

2 Answers 2

5
\$\begingroup\$

Unnecessary Function

Your swap function is unnecessary. Simply replace the function call with this line:

nums[j], nums[j + 1] = nums[j + 1], nums[j]

This does the swapping for you.

Spacing

There should be spaces between values in lists

[1, 2, 3, 4, 5]

between numbers/strings and operators

if nums[j] > nums[j + 1]

and between parameters in a function call

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

Type Hints

Your function header can look like this:

from typing import List, Union

def bubble_sort(nums: List[Union[int, float]]) -> List[Union[int, float]]:

What this says is that the function accepts a list of integers/floats, and returns a list of integers/floats. It adds another layer of descriptiveness to your code.

Docstrings

You should include a docstring at the beginning of every class/method/module you write. This allows you to describe in words what your code is doing.

def bubble_sort(nums: List[Union[int, float]]) -> List[Union[int, float]]:
    """
    A bubble sort algorithm, etc etc etc

    :param nums -> List: A list of integers/floats to sort

    :return List: The sorted list of integers/floats, from smallest -> biggest
    """
\$\endgroup\$
3
\$\begingroup\$

In addition to Linny's answer, one can also optimize the bubble sort algorithm like this:

def bubble_sort(nums):  # sorry that I am too lazy to include type hints here :)
    for i in range(len(nums) - 1):
        found = False
        for j in range(len(nums) - 1 - i):  # start == 0 and step == 1 are unnecessary
            if nums[j] > nums[j + 1]:
                nums[j], nums[j + 1] = nums[j + 1], nums[j]
                found = True  # it means that there is at least a swap
        if not found:  # if there is no swap it means that there is no need to go for next value of i
            break

    return nums

Hope it helps.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.