In the worst case, you find the item in the very last position that takes N steps, i.e. O (N). At best, the element you are looking for is the first, so the complexity is O (1). The average length is the average number of steps. If we do not have an additional context, then this can be done by calculations:
avg = (1 + 2 + ... n) / n = (n * (n + 1) / 2) / n = (n + 1) / 2
If n โ infinity , then adding a positive constant and dividing by a positive constant has no effect, we still have infinity, therefore O (n).
However, if you have large final data to work with, then you can calculate the exact average as described above.
In addition, you may have a context that can help you get extra accuracy in your calculations.
Example:
Consider an example where your array is ordered by frequency in descending order. In case your call to indexOf is use, then the most probable is the first, second, etc. If you have the exact frequency of use for each item, you can calculate the likely time to wait.
Lajos arpad
source share