Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)
edited by

This is my code: 

def largest_to_last(arr, index):

    if(len(arr) == 1):

        return 

    largest_to_last(arr[:-1], index-1)

    if(arr[index-1] > arr[index]):

        arr[index-1], arr[index] = arr[index], arr[index-1]

        # print(arr)

        return

    

arr = [1,4,2,8,5,6]

largest_to_last(arr, len(arr)-1)

print(arr)

I have to push the greatest value to the end of my array using recursion. Any help will be appreciatable. 

1 Answer

0 votes
by (36.8k points)

When you are passing the arr[:-1], the copy of an array is created and changes aren't reflected in your original list.

To implement it:

def sort(arr, index):

    if(len(arr) == 2):

        if(arr[index-1] > arr[index]):

            arr[index-1], arr[index] = arr[index], arr[index-1]

        return arr

    arr = sort(arr[:index], index-1)+[arr[index]]

    if(arr[index-1] > arr[index]):

        arr[index-1], arr[index] = arr[index], arr[index-1]

    return arr

arr = [1,4,2,8,5,6]

arr = sort(arr, len(arr)-1)

print(arr)

Improve your knowledge in data science from scratch using data scientist

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...