quadingle the 2nd
quadingle the 2nd

Reputation: 1

How can I return how many times my list is compared and swapped using selection sort?

I want to return a list where after each iteration, in the list has the number of comparisons and number of swaps. like an output such as this: [[3,1], [2,1], [6,1]] How can I achieve this? Apart from knowing I should add a new [] and append it to that, i dont know how to get the number of comparisons and swaps. any help is appreciated!

def selection_sort(number):
    for pass_num in range(len(number) - 1, 0, -1):
        position_largest = 0
        for i in range(1, pass_num + 1):
            if number[i] > number[position_largest]:
                position_largest = i
        number[position_largest], number[i] = number[i], number[position_largest]

numbers = [90, 78, 54, 22, 73]
print(selection_sort(numbers))

Upvotes: 0

Views: 133

Answers (1)

Scrubject-Zero
Scrubject-Zero

Reputation: 1

I am not very experienced so, sorry if this is not helpful. You should use an global/static integer timer array for both # of comparisons and # of swaps. The comparison variable is incremented every time the conditional statement that makes the comparison runs, and the swap variable is incremented as a part of the code block that makes the swap. Both of these would be done at the active index in arrays parallel to the array being compared.

Upvotes: 0

Related Questions