Search code examples
pythonalgorithmselection-sort

How to split Selection sort into two different functions in python?


Because selection sort divides the input list into two parts: a sublist of sorted items and a sublist of still unsorted items, would it be possible to create two different functions and connect them together? I have my sorting algorithm done but I cannot figure out how to split them.

def selection_sort(l):
    for i in range(len(l)):
        start_index = i

    for j in range(i + 1, len(l)):

        if l[start_index] > l[j]:
            min_value = j

    l[i], l[start_index] = l[start_index], l[i]

l = [64, 25, 12, 22, 11]
print(l)

What I would like to have is to split it into this:

def min_index(l, start_index) & def selection_sort(l)

Solution

  • First of all, the code you have presented is not correct:

    • There is only one swap happening, unconditionally, as the last statement of the function. This cannot be right of course. The number of swaps needed to sort a list varies depending its order.

    • The second loop never iterates: i has reached the length of the input, and so range(i + 1, len(i)) is an empty range.

    • The value of min_value is never used.

    The first two issues are probably because you copied the code in a wrong way, and missed some necessary indentation. The second issue is because of two different names which should really be the same name.

    Here is a corrected version:

    def selection_sort(l):
        for i in range(len(l)):
            start_index = i
    
            for j in range(i + 1, len(l)):
                if l[start_index] > l[j]:
                    start_index = j
    
            l[i], l[start_index] = l[start_index], l[i]
    

    Now to your question: you can indeed put the logic of the inner loop into another function. Like this:

    def min_index(l, i):
        for j in range(i + 1, len(l)):
            if l[i] > l[j]:
                i = j
        return i
    
    def selection_sort(l):
        for i in range(len(l)):
            j = min_index(l, i)
            l[i], l[j] = l[j], l[i]