karec__10
karec__10

Reputation: 23

How do I count these comparisons in selection sort?

Here is my code

count = 0
def selectionSort(data):


    for index in range(len(data)):

        min = index
        count += 1
        # Find the index'th smallest element
        for scan in range(index + 1, len(data)):

            if (data[scan] < data[min]):

                min = scan

        if min != index: # swap the elements
            data[index], data[min] = data[min], data[index]

    return data

data = selectionSort([3,4,5,2,6])


print(count, data)

Upvotes: 1

Views: 2731

Answers (1)

NPE
NPE

Reputation: 500733

Your code as-is should not run. You should get local variable 'count' referenced before assignment.

To fix this, add the following to the top of selectionSort(data):

global count

A better way is to scrap the global variable and return count alongside the sorted data:

def selectionSort(data):
    count = 0
    for index in range(len(data)):
        min = index
        count += 1
        # Find the index'th smallest element
        for scan in range(index + 1, len(data)):
            if (data[scan] < data[min]):
                min = scan
        if min != index: # swap the elements
            data[index], data[min] = data[min], data[index]
    return count, data

count, data = selectionSort([3,4,5,2,6])
print(count, data)

Last but not least, you are counting something other than comparisons. I leave fixing that as an exercise for the reader.

Upvotes: 5

Related Questions