在Python3中带递归的BubbleSort-返回“无" [英] BubbleSort with recursion in Python3 - Returning "None"

查看:58
本文介绍了在Python3中带递归的BubbleSort-返回“无"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个小函数来在Python 3中执行BubbleSort(只是学习如何编码),但我找不到问题.

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

这是代码.由于某种原因,它返回"None".有人可以看看吗?谢谢!

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))

推荐答案

您需要返回已排序的数组

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))

这篇关于在Python3中带递归的BubbleSort-返回“无"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆