Skip to content
Advertisement

Why “None Type” is returned while Selection Sort implementation in Python? [closed]

I’m trying to implement Selection Sort Algorithm in Python and for some reason Sorted Array is returned as None . Here’s the Code:

#Selection Sort
def selection_sort(array):
    for i in range(len(array)):
        min_idx = i
        for j in range(i+1,len(array)):
            if array[j]<array[min_idx]:
                min_idx = j
                
        array[i],array[min_idx] = array[min_idx],array[i]
    

array = [1,7,5,3,9]
print(f"Original Array: {array}")

x=selection_sort(array)
print(f"Sorted Array: {x}")

Output:

Original Array: [1, 7, 5, 3, 9]
Sorted Array: None

Advertisement

Answer

Here is wat u can do:

  1. U have passed a list of values which is passed as reference to the function. so u can get expect the result i.e. the sorted array in the list u passed –> array. so u can do something like this

    print(f"Sorted Array: {array}")
    
  2. if u want to keep the original list intact , pass a copy to the function like below:

    x=selection_sort(array[:])
    

    and return value from your function by adding the the line at the end as below:

    return array
    

    and print as u did in your code

Advertisement