I am trying to learn how the bubble sorting algorithm works in python.
However sorting the list returns None
when i print out the output.
Here Is My Code
arr = ["A", "B", "C", "D", "Z", "Y"]
def _sort(nums):
for i in range(len(nums)-1, 0, -1):
for j in range(i):
if nums[j] > nums[j+1]:
temp = nums[j+1]
nums[j+1] = temp
_sorted = _sort(arr)
print(_sorted)
Here Is Output When I Print Out The Result.
None
First, the algorithm is not right. You should do something like this:
def _sort(nums):
for i in range(len(nums)-1, 0, -1):
for j in range(i):
if nums[j] > nums[i]:
temp = nums[i]
nums[i] = nums[j]
nums[j] = temp
Second, the function does not return anything. That is why it returns None
. However, the list arr
is now sorted. You can check it by running this code:
arr = ["A", "B", "C", "D", "Z", "Y"]
def _sort(nums):
for i in range(len(nums)-1, 0, -1):
for j in range(i):
if nums[j] > nums[i]:
temp = nums[i]
nums[i] = nums[j]
nums[j] = temp
_sort(arr) # This function does not return anything
print(arr)