-1

I have this Python code, is a recursive form of the Selection Sort Algorithm, but it doesn't work, can someone help me?

def selection(lista):
    return selection_aux(lista,0,len(lista))
def selection_aux(lista,i,n):
    if i == n or lista[0]==None:
        return lista
    else:
        num_menor = menor_f(lista,i,n,i)
        temporal = lista[i]
        lista[i] = num_menor
        print(num_menor)
        lista[num_menor] = temporal
        return selection_aux(lista,i+1,n)
def menor_f(lista,j,n,menor):
    if j == n:
        return menor
    if lista[j] < lista[menor]:
        menor = j
        return menor_f(lista,j+1,n,menor)

Test:

>>> selection([1,2,3])

Output

lista[num_menor] = temporal
TypeError: list indices must be integers, not NoneType
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
  • 3
    Can you please add more details as to how it is not working. Something like, what output you expected but what output you got, some logical error, or something like that. – Bhargav Rao May 30 '15 at 21:42
  • Without reading your code carefully, isn't this a bit too long and complicated for something as simple as selection sort? – Shashank May 30 '15 at 21:54
  • Yes, it is, but the idea is write that algorithm by using tail recursion !! – Kendall González May 30 '15 at 21:59

1 Answers1

2

Your indentation was wrong, you did not return anything is if lista[j] < lista[menor] was False so you were setting num_menor to None as all python functions that don't return a value return None by default .

def menor_f(lista,j,n,menor):
    if j == n:
        return menor
    if lista[j] < lista[menor]:
        menor = j
    return menor_f(lista,j+1,n,menor) # dedent 

Cannot follow you variable names as I don't speak what seems to be french, but making the change works for selection([4,3,2])

print(selection([4,3,2]))
[2, 3, 4]

Fails for selection([ 8,3,4,2,5,6]) -> [3, 3, 4, 4, 5, 8] so you need to do some debugging.

Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321