2

I am studying data structures and algorithms and I defined the function [below] to implement the Select Sort Algorithm.... However, the statement for switching minimum values to the beginning of the array doesn't seem to be working. Here is the function definition:

def selectionSort(array: list):
    array_length = len(array)  # this just stores the length of the given list
    _index = 0  # this takes care of dynamically changing the index in which a minimum value is to be found

    for i in array:
        min_value = min(array[_index:array_length])
        if i == min_value:  # if i is the minimum value then do nothing, however update _index
            _index += 1
            continue
        else:  # if i is not the minimum value.... 
            array[_index], array[array.index(min_value)] = min_value, i  # replace i with the minimum number, and move i to the [now previous] position of the minimum number,
            _index += 1  # don'f forget to update _index
    return array

The particular command array[_index], array[array.index(min_value)] = min_value, i doesn't seem to be working and it actually is responsible for switching the position of the minimum value in the array min_value with the currently evaluated value in the array i {if i is not the minimum number min_number}

I have tried testing this function with this array (or list as it is called in python):

[5, 2, 3, 9, 8, 7]

With failed results as the function return the same array that was entered. The reason why I am doing this is that I am trying to see if it is possible to implement a Select Sort algorithm without implementing 2 for loops.

1 Answer 1

2

The line

array[_index], array[array.index(min_value)] = min_value, i

is the same as:

temp = (min_value, i)
array[_index] = temp[0]
array[array.index(min_value)] = temp[1]

First, array[_index] is set to min_value. This means (if not the same minimum value is in a prior index in array) that the following array.index(min_value) returns _index.

Simple solution: Swap expressions:

array[array.index(min_value)], array[_index] = i, min_value
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.