递归插入在python中排序 [英] Recursive Insertion Sort in python

查看:82
本文介绍了递归插入在python中排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用python编写所有排序算法的迭代和递归版本. 除了我什么都没退的事实之外,这又有什么问题呢?我的切片有问题吗?

I am trying to write iterative and recursive versions of all the sorting algorithms in python. Other than the fact that I am not returning anything, what is wrong with this? Is it a problem with my slicing?

尝试解决方案:

    def insertOne(element, aList):
    ''' Inserts element into its proper place in a sorted list aList.
        input: element is an item to be inserted.  aList is a sorted list.
        output: A sorted list.
    '''
    if len(aList) == 0:
        return [element]
    elif element < aList[0]:
        return [element] + aList
    else:
        return aList[0:1] + insertOne(element, aList[1:])





    def sort(aList):

    if len(aList) == 0:
        return []

    n = len(aList)
    if n > 1:
        sort(aList[:n - 1])
        insertOne(n, aList)




     aList = [3,2,1]

     print sort(aList)  

推荐答案

您的sort方法错误. naList的长​​度,不是元素.您不想将其放在列表中,这就是您使用insertOne(n, aList)所做的事情.

Your sort method is wrong. n is the length of aList, not an element. You wouldn't want to put it in the list, which is what you're doing with insertOne(n, aList).

您要执行的操作是:

def sort(aList):
  if len(aList)<=1:
    return aList
  else:
    return insertOne(aList[0], sort(aList[1:]))

基本上,您要遍历aList,并使用insertOne将遇到的每个元素插入其正确位置.

Basically, you're going through aList, and inserting every element you encounter in its correct position using insertOne.

这篇关于递归插入在python中排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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