BubbleSort with recursion in Python3 - Returning “None”

社会主义新天地 提交于 2021-02-05 07:45:12

问题


I created a small function to do BubbleSort (just learning how to code) in Python 3 and I can't find the issue.

Here is the code. It's returning "None" for some reason. Could someone please take a look? Thank you!

arr = [1,5,2,7,3]

def bubbleSort(array):
    count = 0
    #print("array is currently",array)
    for idx in range(len(array)-1):
        if array[idx] > array[idx + 1]:
            array[idx],array[idx + 1] = array[idx + 1],array[idx]
            count += 1
            #print("swaped and count is currently",count)
            #print("array is currently",array)
    if count == 0:
        #print("Count is zero")
        #print("array is currently",array)
        return array
    else:
        #print("Count is not zero")
        bubbleSort(array)

print(bubbleSort(arr))

回答1:


You need to return the sorted array

arr = [1,5,2,7,3]

def bubbleSort(array):
    count = 0
    #print("array is currently",array)
    for idx in range(len(array)-1):
        if array[idx] > array[idx + 1]:
            array[idx],array[idx + 1] = array[idx + 1],array[idx]
            count += 1
            #print("swaped and count is currently",count)
            #print("array is currently",array)
    if count == 0:
        #print("Count is zero")
        #print("array is currently",array)
        return array
    else:
        #print("Count is not zero")
        return bubbleSort(array)

print(bubbleSort(arr))



回答2:


Bubble sort using recursion without using any loop,

def bubble_sort_recur(a, i, j, n):
    if j == n:
        i = i+1
        j = 0
    if i == n:
        return 
    if a[i] > a[j]:
        temp = a[j]
        a[j] = a[i]
        a[i] = temp
        bubble_sort_recur(a, i, j+1, n);
    else:
        bubble_sort_recur(a, i, j + 1, n);
    return a

a = [1, 12, 3, 4]
a = bubble_sort_recur(a, 0, 0, len(a))
print(a)



回答3:


A simplest solution with less line of code:

def bubblesort(l,n):
    for i in range(len(l)-2):
        if l[i] > l[i+1]:
            l[i], l[i+1] = l[i+1], l[i]
    if n>1:        
        bubblesort(l,n-1)   

l = [6,2,9,11,9,3,7,12]
n=len(l)    
bubblesort(l,n)
print(l)


来源:https://stackoverflow.com/questions/51146458/bubblesort-with-recursion-in-python3-returning-none

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!