Recall that using the sort
method on an array of numbers
produced an unexpected result, since JavaScript converts
the numbers to strings by default. Let's fix this!
Here is one approach to sorting an array:
Create a function with an array of numbers as its parameter. The function should iterate through the array and return the minimum value from the array.
Hint: Use what you know about if
statements to identify and
store the smallest value within the array.
Tip
Use this sample data for testing.
1[ 5, 10, 2, 42 ]
2[ -2, 0, -10, -44, 5, 3, 0, 3 ]
3[ 200, 5, 4, 10, 8, 5, -3.3, 4.4, 0 ]
Create another function with an array of numbers as its parameter. Within this function:
Code studio part B at repl.it.
Tip
Which type of loop?
Either a for
or while
loop will work inside this function, but one
IS a better choice. Consider what the function must accomplish vs. the
behavior of each type of loop. Which one best serves if the array has an
unknown length?
The sorting approach used above is an example of a selection sort. The function repeatedly checks an array for the minimum value, then places that value into a new container.
Selection sorting is NOT the most efficient way to accomplish the task, since it requires the function to pass through the array once for each item within the array. This takes way too much time for large arrays.
Fortunately, JavaScript has an elegant way to properly sort numbers.
Tip
Here is a nice, visual comparison of different sorting methods.
Feel free to Google "bubble sort JavaScript" to explore a different way to order numbers in an array.
If you Google "JavaScript sort array of numbers" (or something similar), many options appear, and they all give pretty much the same result. The sites just differ in how much detail they provide when explaining the solution.
One reference is here: W3Schools.
End result: the JavaScript syntax for numerical sorting is
arrayName.sort(function(a, b){return a-b});
.
Here, the anonymous function determines which element is larger and swaps the
positions if necessary. This is all that sort
needs to order the entire
array.
Using the syntax listed above:
arrayName
?arrayName
?Each programming language (Python, Java, C#, JavaScript, etc.) has built-in sorting methods, so why did we ask you to build one?
It's kind of a programming rite of passage - design an efficient sorting function. Also, sorting can help you land a job.
As part of a tech interview, you will probably be asked to do some live-coding. One standard, go-to question is to sort an array WITHOUT relying on the built in methods. Knowing how to think though a sorting task, generate the code and then clearly explain your approach will significantly boost your appeal to an employer.
Refactor your sorting function from Part B to use recursion.