2

I am trying to check if a list is sorted using recursion in python. Returns true if sorted, False if not sorted.

def isSorted(L):
    if len(L) < 2:
       return True

Now, I am not sure what I should be doing next.Please help!

1
  • You should write a unit test for this :) And then assert that a list of x items is in the correct order. Commented May 5, 2014 at 5:37

1 Answer 1

6

Check first two items.

If they are ordered, check next items using recursion:

def isSorted(L):
    if len(L) < 2:
        return True
    return L[0] <= L[1] and isSorted(L[1:])

Side note The function can be expression as a single expression as thefourtheye commented:

return len(L) < 2 or (L[0] <= L[1] and isSorted(L[1:]))
Sign up to request clarification or add additional context in comments.

3 Comments

return len(L) < 2 or (L[0] <= L[1] and isSorted(L[1:]))?
+1. Could also avoid the list copy by taking in an extra argument for the index of the current element and increment this index in the recursive calls. Then define a wrapper to pass in the initial index set to 0. Base case will change to whether idx >= len(L) -1. But this captures the gist. Nice.
If you split the list in half at each step, the recursion depth will be log2(n)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.