Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

111
Views
How to make this javascript ordering consecutive integers ascending by swaps function more efficient?

Object is to order ascending an unordered list of consecutive integers 1,2,3.....n by swapping numbers (say swapping values at indices 3 and 6), and find the minimum number of swaps needed. My code works, but times out (10 second limit) when given the edge case 100000 integers. How can I streamline this code? To me it feels fairly minimal already - no nested loops or anything. I'm not very experienced with efficiency evaluation, any help would be appreciated, thanks.

function minimumSwaps(arr) {
    var swaps = 0;
    for (var i = 0; i < arr.length; i++) {
        if (arr[i] !== i+1) {
            var tempIndex = arr.indexOf(i+1);
            var tempVal = arr[i];
            arr[i] = i+1;
            arr[tempIndex] = tempVal;
            swaps += 1;
    }
  }
  //console.log(swaps)
  return swaps;
}
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!