1

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]

1 Answer 1

4

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.