1

How could I implement this using recursion, and would it be more effcient?

My code:

def insertionSort(array):
    '''(list) - > list
    Returns a sorted list of integers by implementing
    the insertion sort which returns numbers in array from
    least to greatest
    '''
    for i in range(1, len(array)):

        if array[i-1] > array[i]: #Finds a number out of place
            temp = array[i]
            for a in range(0,i):
                if temp < array[a]:
                    array.insert(a,temp)
                    del array[i+1]
                    break
    return array
9
  • No it isn't more efficient to use recursion, it is usually much more costly, also have you attempted implementing recursion yourself? Commented Mar 23, 2013 at 5:45
  • @jamylak Doesnt Python optimize recursion, and that too by quite a bit ? I have seen some posts here on SO with time measurements that would suggest almost equivalent performance from both recursion and iteration. Commented Mar 23, 2013 at 5:48
  • 1
    @AshRj Which posts are you talking about? Python recursion is notably slow Commented Mar 23, 2013 at 5:49
  • 1
    my "seems like a homework" senses are starting to tingle! Commented Mar 23, 2013 at 5:56
  • 2
    Related: Does Python optimize tail recursion? (Answer: no) Commented Mar 23, 2013 at 6:14

2 Answers 2

4

A simple recursive version:

def insertionSort(array,i=1):
  if i >= len(array):
    return array
  if array[i-1] > array[i]: 
    temp = array[i]
    for a in range(0, i): 
      if temp < array[a]:
        array.insert(a,temp)
        del array[i+1]
        break
  return insertionSort(array, i+1)

Generally recursion is better for certain data structures such as trees and linked lists. Sometimes it is easier to think in terms of recursion to solve a problem. I don't remember a case where recursion actually used for efficiency.

Sign up to request clarification or add additional context in comments.

Comments

0

Any for loop for x in range(a,b): Body can be reimplemented with tail recursion:

def rfor(b, x = a):
  if a < b:
     Body
     rfor(b, x + 1)

This ought to give you enough to get the answer yourself. In standard Python this will definitely be slower than the loop and eat one stack frame per iteration. In other languages and implementations with good tail call optimization, they'll be equal in cost. Apparently Guido has said he's uninterested in tail call optimization.

Comments

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.