简体   繁体   English

数组排序的顺序递归

[英]Array sorted order recrusion

Below is code for checking whether a given array is sorted.下面是用于检查给定数组是否已排序的代码。 Tried putting in a print command at various stages to understand the code line by line, but to no avail.尝试在各个阶段输入打印命令以逐​​行理解代码,但无济于事。

def sort(a):

    if len(a) == 1:
       return True
    return a[0] <= a[1] and isSorted(a[1:])

a =[127,220,246,277,321,454,534,565,933]

print(sort(a))

Firstly首先
This is throwing an error这是抛出错误

NameError: name 'isSorted' is not defined. NameError: name 'isSorted' 未定义。

Second第二
The whole code seems like a shorthand.整个代码似乎是一个速记。 There is no else after if, why is the isSorted only looking from index position 1. This is supposed to a recursive function, can't see one. if后面没有else了,为什么isSorted只从索引位置1看。这个应该是递归函数,看不到。

Your function name is sort and not isSorted , and when you are writing print(sort(a)) , you are not returning the array, you are checking if this array is already sorted.您的函数名称是sort而不是isSorted ,并且在编写print(sort(a)) ,您没有返回数组,而是检查此数组是否已排序。

You should do:你应该做:

def sort(a):
    if len(a) == 1:
        return True
    return a[0] <= a[1] and sort(a[1:])

a =[127,220,246,277,321,454,534,565,933] 
print(sort(a))

and the output:和输出:

True

Second - the whole code seems like a shorthand.其次 - 整个代码似乎是一个速记。 There is no else after if, why is the isSorted only looking from index position 1. This is supposed to a recursive function, can't see one. if后面没有else了,为什么isSorted只从索引位置1看。这个应该是递归函数,看不到。

You don't need an else statement.你不需要 else 语句。 And if starts from index position 1, because it checks if the array is sorted in index 0, and index 1 recursively on the array.如果从索引位置 1 开始,因为它检查数组是否在索引 0 中排序,并在数组上递归索引 1。 The code go to the last index, until the length is 1, and then it goes back recursively, to check if a[0] <= a[1] .代码转到最后一个索引,直到长度为 1,然后递归返回,检查是否a[0] <= a[1] You should practice more on recursion.你应该多练习递归。

You can try this:你可以试试这个:

def is_sorted(array):
   if not array[1:]:
       return True
   if array[0] <= array[1]:
       return is_sorted(array[1:])
   return False

print(is_sorted([56, 100, 234, 250, 300]))
print(is_sorted([506, 100, 24, 250, 300]))

Output:输出:

True
False

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM