skip to Main Content

This code is run on a compiler in a Microsoft Edge browser in case the sorting algorithm of the browser matters.

Solving an algorithm question online and it kept failing a "Must be valid for any given input" test case. Looked online and found an answer to the question. In the code I found online, it arranges the strings in an array (named ‘ordering’) according to their character count by using –

ordering = [ 'she', 'lives', 'with', 'him', 'in', 'a', 'small', 'apartment' ];

ordering.sort(function(a,b){return a.length-b.length;}) 

The way I tried to arrange the strings were by (didn’t know of the array.sort() function before this) –

for(var i = 0; i < ordering.length-1; i++){
    for(var j = i+1; j < ordering.length; j++){
        if(ordering[j].length < ordering[i].length){
            temp = ordering[i]; /
            ordering[i] = ordering[j];  
            ordering[j] = temp; 
        }
    }
}

But, my code would keep failing the test case but whenever I replace it with the former method the test case is passed. I’m confused as to whether these two behave differently or not.

2

Answers


  1. If you want to sort the array according to the length of the words:

    const ordering = [ 'she', 'lives', 'with', 'him', 'in', 'a', 'small', 'apartment' ];
    
    console.log(ordering.sort(function(a,b){return a.length - b.length;})) ;
    Login or Signup to reply.
  2. Here is the working code in second way

    const ordering = [ 'she', 'lives', 'with', 'him', 'in', 'a', 'small', 'apartment' ];
    for (let i = 0; i < ordering.length - 1; i++) {
      for (let j = i + 1; j < ordering.length; j++) {
        if (ordering[i].length > ordering[j].length) {
          const temp = ordering[i];
          ordering[i] = ordering[j];
          ordering[j] = temp;
        }
      }
    }
    console.log(ordering);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search