0
def sel(unsort,current):
    if len(unsort) == 0:
        return current

    temp = unsort[0]    
    for i in range(len(unsort)):
        if unsort[i]<temp:
            temp = unsort[i];

    unsort.remove(temp)
    current = current + [temp];

sel(unsort,current)

Above will define a function selection sort.

a = [4,3,2,1];
print(sel(a, []))

When I run the program on python, it print "None". The function should return current as a list. What have I done wrong here?

smci
  • 32,567
  • 20
  • 113
  • 146
user45765
  • 135
  • 4
  • Please indent and format your code properly. The line `sel(unsort,current);` is indented wrong, it can't occur inside the function `sel()`. Also, Python doesn't use semicolons. And it doesn't use unnecessary parentheses, so `if len(unsort) == 0:` , without parens. – smci Jun 18 '20 at 01:26
  • @smci Is there instruction on how to indent properly on the forum? It seems that when I put code in the post, it will not indent as I had on python. I see that semicolon is not used as terminator. Thanks. – user45765 Jun 18 '20 at 01:33
  • Yes please read through [SO Help](https://stackoverflow.com/help) and [Meta: How do I format my code blocks?](https://meta.stackoverflow.com/questions/251361/how-do-i-format-my-code-blocks) – smci Jun 18 '20 at 18:49
  • Also (obviously), your function never returns anything, as @JonathonReinhart pointed out. The last line of a fn is typically a return statement. Otherwise, any local changes you make to a local copy of the `unsort` arg disappear when the fn ends, i.e. the result of the fn is thrown away, not what you want. See [How do I pass a variable by reference?](https://stackoverflow.com/questions/986006/how-do-i-pass-a-variable-by-reference) – smci Jun 18 '20 at 18:51

1 Answers1

2

When you recursively call sel, you ignore the return value.

Change it to return:

    return sel(unsort, current)
Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328