0

I'm trying to run selection sort in python, this is the code that I'm using

def main(list):
    input_array = [12, 9, 13, 7, 3, 19, 6, 5]
    output_array = selection_sort(input_array)
    print(output_array)


def selection_sort(param):

    for i in range(0, (len(param) - 1)):
        min = i
        for j in range(i + 1, len(param)):
            if param[min] < param[j]:
                min = j

            if min != i:
                temp = param[i]
                param[i] = param[min]
                param[min] = temp
    return param

The output that I get is

Process finished with exit code 0

I'm using PyCharm as the idea, if that's of any consequence.

1
  • 1
    how can min, i, j, temp = 0 work? You are also shadowing the builtin list and the builtin min Commented Jul 12, 2014 at 12:12

2 Answers 2

2
  • input_array should be a list, you are making it a set

    input_array = [12, 9, 13, 7, 3, 19, 6, 5]
    
  • don't use the variable name list, it is the name for the built-in list

  • don't use min as a variable name, it is the name for the built-in function min
  • you don't need an argument for your main method here
  • you are not calling your main method, call it after the definition of selection_sort
  • change the line

    minimum, i, j, temp = 0
    

    to

    minimum, i, j, temp = 0, 0, 0, 0
    
Sign up to request clarification or add additional context in comments.

2 Comments

This code seems to work but I've a few questions, one the output array is largest first, second why have you reversed the sequence of the functions and why're you calling main() in the end. I'm a bit new to python.
Hey Clockwork. You could also put the definition of main before the definition of selection_sort, as long as you still issue the call to main at the end of the script. I am explicitly calling main at the end because main is just a function, and if you want it to run, you need to call it. This behavior is different to Java, where the main method is called automatically. The elements of the result are in descending order because you coded it that way :) Have another look at your logic, or reverse the list with list(reversed(output_array)).
0

This will sort in ascending order:

def selection_sort(my_list):
    for j in range(len(my_list)):
        for i in range(j, len(my_list)):
            if my_list[i] < my_list[j]:
                my_list[j], my_list[i] = my_list[i], my_list[j]
    return my_list



def main():
    input_array = [12, 9, 13, 7, 3, 19, 6, 5]
    output_array = selection_sort(input_array)
    print(output_array)
[3, 5, 6, 7, 9, 12, 13, 19]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.