对整数列表进行排序的递归函数 [英] A recursive function to sort a list of ints

查看:63
本文介绍了对整数列表进行排序的递归函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想定义一个递归函数,可以对任何整数列表进行排序:

def sort_l(l):如果 l==[]:返回 []别的:如果 len(l)==1:返回 [l[-1]]elif l[0]

在列表 [3, 1, 2,4,7,5,6,9,8] 上调用这个函数应该给我:

[1,2,3,4,5,6,7,8,9]

但我明白了:

print(sort_l([3, 1, 2,4,7,5,6,9,8]))-->[1, 2, 4, 5, 6, 8, 9, 7, 3]

请帮我解决问题,实际代码将不胜感激.谢谢!

解决方案

快速排序是递归且易于在 Python 中实现:

def quick_sort(l):如果 len(l) <= 1:返回 l别的:return quick_sort([e for e in l[1:] if e <= l[0]]) + [l[0]] +\quick_sort([e for e in l[1:] if e > l[0]])

会给:

<预><代码>>>>quick_sort([3, 1, 2, 4, 7, 5, 6, 9, 8])[1, 2, 3, 4, 5, 6, 7, 8, 9]

I want to define a recursive function can sort any list of ints:

def sort_l(l):
    if l==[]:
        return []
    else:
        if len(l)==1:
            return [l[-1]]
        elif l[0]<l[1]:
            return [l[0]]+sort_l(l[1:])
        else:
            return sort_l(l[1:])+[l[0]]

Calling this function on a list [3, 1, 2,4,7,5,6,9,8] should give me:

[1,2,3,4,5,6,7,8,9]

But I get:

print(sort_l([3, 1, 2,4,7,5,6,9,8]))--> [1, 2, 4, 5, 6, 8, 9, 7, 3]

Please help me to fix the problem, actual code would be appreciated. Thanks!

解决方案

The quick sort is recursive and easy to implement in Python:

def quick_sort(l):
    if len(l) <= 1:
        return l
    else:
        return quick_sort([e for e in l[1:] if e <= l[0]]) + [l[0]] +\
            quick_sort([e for e in l[1:] if e > l[0]])

will give:

>>> quick_sort([3, 1, 2, 4, 7, 5, 6, 9, 8])
[1, 2, 3, 4, 5, 6, 7, 8, 9]

这篇关于对整数列表进行排序的递归函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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