August 2024
Intermediate to advanced
516 pages
11h 47m
English
In the next example, we create a function that takes a small sample of an array. We expect to have very large arrays, so our sample is just the first, middlemost, and last value from the array.
Here’s an implementation of this function. See if you can identify its efficiency in Big O:
| | function sample(array) { |
| | if (array.length === 0) { return null; } |
| | |
| | const first = array[0]; |
| | const middle = array[Math.floor(array.length / 2)]; |
| | const last = array[array.length - 1]; |
| | |
| | return [first, middle, last]; |
| | } |
In this case again, the array passed into this function is the primary data, so we can say that N is the number of elements in this array.
However, our function ends up taking the same number of steps no matter ...
Read now
Unlock full access