2

I'm going through some basic array challenges on w3.

Here is the task given:

Write a JavaScript program to sort the items of an array.

Sample array : var arr1 = [ 3, 8, 7, 6, 5, -4, 3, 2, 1 ]; Sample Output : -4,-3,1,2,3,5,6,7,8

Here is their given solution:

    var arr1=[-3,8,7,6,5,-4,3,2,1];  
var arr2=[];  
var min=arr1[0];  
var pos;  
max=arr1[0];  
for (i=0; i<arr1.length; i++)  
{  
        if (max<arr1[i]) max=arr1[i];  
}  

for (var i=0;i<arr1.length;i++)  
{  
        for (var j=0;j<arr1.length;j++)  
        {  
                if (arr1[j]!="x")  
                {  
                        if (min>arr1[j])   
                        {  
                                min=arr1[j];  
                                pos=j;  
                        }  
                }  
        }  
        arr2[i]=min;  
        arr1[pos]="x";  
        min=max;  
}  
alert(arr2);  

This is what I came up with... :

var arr1 = [ -3, 8, 7, 6, 5, -4, 3, 2, 1 ];

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

console.log(arr1);

Why does it seem to me that their solution is so much more "convoluted"? Is it necessary to add their solution to protect against a specific use case?

someoneHere
  • 323
  • 1
  • 3
  • 15
  • 1
    No, but is it good to know how to wrap your head into how to do it without using native methods? Might be why it was done that way – charlietfl Jan 04 '16 at 01:20

1 Answers1

0

To sort an array, always use built-in functions rather that writing your own. It takes away the pain of useless debugging and, actually, re-inventing the wheel.

.sort() is absolutely OK.

Moreover, not only the long solution is "convoulted", it's O(n^2) whist the native sort is usually faster.

And it's doing some weird stuff with the 'x' value and uses == instead of ===, so it looks not so good at all.

Community
  • 1
  • 1
Alexander Mikhalchenko
  • 4,525
  • 3
  • 32
  • 56
  • yeah. I think I've lost trust in their "solutions". Any recommendations on better code challenges / drills. Aside from writing your own programs (which, I'm doing)? – someoneHere Jan 04 '16 at 01:18
  • @someoneHere probably, as mentioned by charlietflm the point was to learn how to write a simple sort yourself but it does not take away any other issues. As far as I know, codescool.com has nice tutorials – Alexander Mikhalchenko Jan 04 '16 at 01:24
  • Yeah. I feel that should have been included in their objective, though . I can write working code and understand for loops, etc. Working more towards writing more clean/ maintainable code at this point. – someoneHere Jan 04 '16 at 01:39