Minimum swaps algorithm terminated due to timeout I have been trying to solve this question.  


  Given an unordered array consisting of consecutive integers [1, 2, 3, …, n], find the minimum number of two-element swaps to sort the array.


I was able to solve it but my solution's complexity is not good enough that it terminated due to a timeout when it runs with bigger arrays. This is a typical problem for me, I always solve the problem somehow but the complexity is not optimal and the solution does not pass the all the cast cases. If you have any suggestions for me for the future interview questions like that, I'd appreciate knowing how should I approach the questions.

function findIndice(arr,i){
  let iterator=0
  while(arr[iterator]!==i+1){
    iterator++
  }
  return iterator
}

function swap(arr,x,y){
  let temp=arr[x]
  arr[x]=arr[y]
  arr[y]=temp
}



function minimumSwaps(arr){
  let i=0;
  let counter=0;
  let size=arr.length;

  for(i=0;i&lt;size-1;i++){
    if(arr[i]!==i+1){
      let index=findIndice(arr,i)
      swap(arr,index,i)
      counter++
    }
  }
  return counter
}
Your algorithm can be summarized by the pseudocode:

for each position in the array
    if a position is occupied by the wrong number
        find the number that fits into the position
        perform a swap


A better algorithm would be:

for each position in the array
    if a number is in the wrong location
        find the position the number should go
        perform a swap


This is because finding a number for a given location requires a linear scan, but finding the location for a given number is as simple as it gets: the number five should go into the fifth position.

The full program could look like this (in python, as I don't speak js):

def minimumSwaps(arr):
    def swap(i, j):
        arr[i], arr[j] = arr[j], arr[i]
    swaps = 0
    for i in range(0, len(arr)):
        while arr[i]-1 != i:
            swap(i, arr[i]-1)
            swaps += 1
    return swaps