简体   繁体   中英

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.

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.

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.

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.

You don't need an else statement. 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. 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] . 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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