Home > other >  what's wrong with my selection sorting program? output is printing the same array instard of so
what's wrong with my selection sorting program? output is printing the same array instard of so

Time:10-29

def selectionSort(arr):
    n = len(arr)

    for i in range(n-1):
        minValueIndex = i
        for j in range(i   1, n):
            if arr[i] < arr[minValueIndex]:
                minValueIndex = j

        if minValueIndex != i:
            temp = arr[i]
            arr[i] = arr[minValueIndex]
            arr[minValueIndex] = temp

    return arr

a = [2,32,0,1,9,54,7]

print(selectionSort(a))

output is not a sorted list, why?

i was expecting a sorted list but the list is printing as it is.

CodePudding user response:

you just have to replace

if arr[i] < arr[minValueIndex]:

with

if arr[j] < arr[minValueIndex]:

CodePudding user response:

Switch the command:

if arr[i] < arr[minValueIndex]: 

with:

if arr[j] < arr[minValueIndex]:

And it should work fine.

  • Related