I am trying to write iterative and recursive versions of all the sorting algorithms in python. Other than the fact that I am not returning anything, what is wrong with this? Is it a problem with my slicing?
Attempt at solution:
def insertOne(element, aList):
''' Inserts element into its proper place in a sorted list aList.
input: element is an item to be inserted. aList is a sorted list.
output: A sorted list.
'''
if len(aList) == 0:
return [element]
elif element < aList[0]:
return [element] + aList
else:
return aList[0:1] + insertOne(element, aList[1:])
def sort(aList):
if len(aList) == 0:
return []
n = len(aList)
if n > 1:
sort(aList[:n - 1])
insertOne(n, aList)
aList = [3,2,1]
print sort(aList)
ifandfor; this code will fail on line 1 with an IndentationError.aList[:n - 1]is a new, independent list constructed fromaList; sorting it won't affectaListat all. Similarly, returning something frominsertOnewon't affect the value ofaList.insertOneis supposed to take an element to insert and a sorted sublist to insert into, butinsertOne(n, aList)passes an index and a partially sorted list that already contains the element you want to insert.