Faisal Khan
Faisal Khan

Reputation: 113

Selection sort implementation in python

I am trying to implement a selection sort in python, which I have done so far. The output of this function is not sorted at all. What do you think I am doing wrong here? as I am storing the index of the smallest element in the array and swapping that. If someone can point out the flaw in my logic this would serve as an example for others doing the same thing.

def selection_sort(array):
    for i in range(len(array)):
        index = 0
        smallest = array[i]
        for j in range(len(array)):
            if array[j] < smallest:
                smallest = array[j]
                index = j
        temp = array[i]
        array[i] = smallest
        array[index] = temp
    return array


to_sort = [99, 44, 6, 2, 1, 5, 63, 87, 283, 4, 0]
print(selection_sort(to_sort))

Output: [44, 6, 2, 1, 5, 63, 87, 283, 4, 99, 0]

Upvotes: 1

Views: 56

Answers (1)

trincot
trincot

Reputation: 349974

Selection sort looks ahead from the current index i, so the inner loop should only iterate over that range. Secondly the index should be initialised at the current i, as it must indicate where smallest comes from:

def selection_sort(array):
    for i in range(len(array)):
        index = i  # corrected
        smallest = array[i]
        for j in range(i + 1, len(array)):  # corrected
            if array[j] < smallest:
                smallest = array[j]
                index = j
        temp = array[i]
        array[i] = smallest
        array[index] = temp
    return array

Upvotes: 4

Related Questions