Learn practical skills, build real-world projects, and advance your career
Created 4 years ago
In this code we need to sort a list using Recursion
First Approach
def isSorted(arr):
if len(arr)==0 or len(arr)==1:
return True # because list of length 0 or 1 are already sorted
if arr[0] > arr[1]: # checking if the first element is greater than the second element because then the list won't be
return False # a sorted list
#now we are going to send the smaller list which is the entire list except the first element again for checking the sorted order
if isSorted(arr[1:] # this is the "most hearbreaking step" because we are sending a copy of the list again to our function which will be consuming a lot of space.
):
return True
else:
return False
arr=[1,3,4,7,3,6,9,0]
print(isSorted(arr))
False
arr = [1,2,5,9,15]
print(isSorted(arr))
True