Skip to content

feat(sorts): add bubble sort algorithm for beginners #11641

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 5 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions sorts/simple_bubble_sort.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
def bubble_sort(nums: list[int]) -> list[int]:
"""
param nums: the array of integers(int) because this application does not use decimal numbers, but if needed, use float type.

Check failure on line 3 in sorts/simple_bubble_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (E501)

sorts/simple_bubble_sort.py:3:89: E501 Line too long (128 > 88)
:return: the same nums list ordered by ascending

Examples:
>>> bubble_sort([8, 2, 4, 5, 7, 0])
[0, 2, 4, 5, 7, 8]

step 01: create the nums array
step 02: collect the dimension of array
step 03: defines the number of times your array will be traversed according to the number of elements

Check failure on line 12 in sorts/simple_bubble_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (E501)

sorts/simple_bubble_sort.py:12:89: E501 Line too long (105 > 88)
step 04: for each pair of elements in the array, starting from the Index, reorder them.

Check failure on line 13 in sorts/simple_bubble_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (E501)

sorts/simple_bubble_sort.py:13:89: E501 Line too long (91 > 88)
Elements already in the correct order will not be modified in the Loop -> (0, n - 1 - i)

Check failure on line 14 in sorts/simple_bubble_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (E501)

sorts/simple_bubble_sort.py:14:89: E501 Line too long (92 > 88)
step 05: the numbers are compared to arrive at the required order
step 06: the nuns list is returned in ascending order! :)
"""
n = len(nums) # 02
for i in range(n): # 03
for j in range(0, n - 1 - i): # 04

Check failure on line 20 in sorts/simple_bubble_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (PIE808)

sorts/simple_bubble_sort.py:20:24: PIE808 Unnecessary `start` argument in `range`
if nums[j] > nums[j + 1]: # 05
nums[j], nums[j + 1] = nums[j + 1], nums[j]
return nums


nums = [65, 66, 12, 4, 9, 10, 32, 2] # 01
ordered_nums = bubble_sort(nums) # 06
print("The result:", ordered_nums)

if __name__ == "__main__":
import doctest

doctest.testmod()
Loading