Home > Software engineering >  Cannot swap values in for loop in python in the first iteration
Cannot swap values in for loop in python in the first iteration

Time:10-28

I am trying to find the minimum swaps to sort an array without duplicates in python.I have the following code and i am using the greedy approach where i sort the array and compare and swap accordingly

def minimumSwaps(arr):
    totalswapcount=0
    sortedarr=sorted(arr)
    for x in range(0,len(arr)-1):
        if (arr[x]!=sortedarr[x]):
            totalswapcount =1
            
            arr[x],arr[arr.index(sortedarr[x])]=arr[arr.index(sortedarr[x])],arr[x]
            
    print(totalswapcount)
    
minimumSwaps([2,3,4,1,5])

The code does not swap on the first iteration with this dry run for some reason.The array is repeated and hence it adds an iteration to the final result.Here is the result of this dry run enter image description here

I was expecting that after the first repetition the array would become [1,3,4,2,5] where 1 and 2 is swapped since 2 occupies 1's real position but it stays the same instead

CodePudding user response:

When you assign to

arr[x],arr[arr.index(sortedarr[x])]=

it calculates the subscript arr.index(sortedarr[x]) after it has already assigned to arr[x]. Get the index outside the spread assignment, so it will use the new index of the element if the element has been moved into a lower index.

        if (arr[x]!=sortedarr[x]):
            totalswapcount =1
            y = arr.index(sortedarr[x])
            arr[x], arr[y] = arr[y], arr[x]
  • Related