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

211
Views
Would this be a proper implementation of selection sort in javascript

Would the code below be the appropriate of implementing selection sort in Javascript?

let array = [24,27,43,11,32,7]; 
let temp; 

for(i = 0; i<array.length; i++){
    for(j =0; j<array.length; j++){
        if(array[i] < array[j]){
            temp = array[i]; 
            array[i] = array[j]; 
            array[j] = temp; 
        }
    }
}

console.log(array); 

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

No.

With selection sort, you build up the sorted segment on the left side of the array in pieces by swapping the lowest value from the unsorted section with the next unsorted index. For an array of length N, there should be only N swaps - your approach is swapping many more times because it's not breaking to the next i after a swap. You also aren't identifying the lowest value in the unsorted section.

In the nested loop (over j), you should

  • Start at the current value of i, not at 0 (because the portion of the array from 0 to i should already be sorted)
  • Identify the index of the lowest value in the segment from j to the end of the array - this could be done with Math.min followed by indexOf, or by saving a variable of the lowest value found so far as well as its index, or with many other ways
  • Swap that index with the i index, then break so as to go onto the next iteration of i

That said - if this is anything other than an algorithm exercise, I'd highly recommend using the built-in Array.prototype.sort method for sorting an array; it's more concise, makes more sense at a glance, and is far faster.

about 4 years ago · Juan Pablo Isaza Report
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!