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
If you want to sort the array according to the length of the words:
Here is the working code in second way