递归函数对数组进行排序 [英] Recursive function to sort an array

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

问题描述

我在构建对整数数组排序的递归函数时遇到了麻烦。目前,我不知道任何排序算法,这只是我的第二门CS课程。我在这里看到了很多解决方案,但是这些解决方案的问题在于它们具有循环或嵌套的条件语句。在此函数中,我不能使用循环或嵌套的if语句,而只能使用单个if / else语句。

I'm having trouble building a recursive function that sorts an integer array. At this point, I don't know any sorting algorithms, this is only my second CS course. I've seen a lot of solutions on here, but the issue with those solutions is that they have loops or nested conditions statements. In this function I cannot use loops or nested if statements, only single if/else statements.

我知道你们不想简单地给出答案,因为它带走了学习经验,但是如果我能指出正确的方向,我会极大地

I know you guys don't want to simply give answers since it takes away from the learning experience, but if I could just get pointed in the right direction I would greatly appreciate it.

推荐答案

编写递归函数-


  1. 编写一个函数签名,并假设它会用一些魔术来完成您的工作。

  1. Write a function signature and assume that it will do your job with some magic.

现在考虑基本条件,即什么

Now think about base condition i.e what will your function do in case of smallest valid input.

现在编写归纳步骤,在较小的输入上调用相同的函数(通常

Now write the induction step in which you call the same function on smaller input(generally).

def sorting(arr):

    #Base Condition
    if len(arr) == 1:
        return

    #Induction
    last_num = arr[-1]
    arr.pop()
    sorting(arr)
    insert(arr, last_num)

    return arr

def insert(arr, last_num):

    #Base Condition
    if len(arr) == 0 or arr[-1] <= last_num:
        arr.append(last_num)
        return

    #Induction
    val = arr[-1]
    arr.pop()
    insert(arr, last_num)
    arr.append(val)



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

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