How to most efficently find the index of an item in an array with only two types of items 0, 1 in javascript -


say instance have

var arr = [0,0,0,1,0,1,1,0,0,0,1]; 

and want find position of first 1 reference first 0. arr.indexof solve problem directly i'm not sure if compares linearly each item in array? binary search wouldn't work because loose index if sort , element... other way first 1 , aha! index 3, without going 1 element @ time?

it searches iteratively beginning of array.

the relevant part of specification:

repeat, while k < len

  • let k present result of calling [[hasproperty]] internal method of o argument tostring(k).
  • if k present true,
    • let elementk result of calling [[get]] internal method of o argument tostring(k).
    • let same result of applying strict equality comparison algorithm searchelement , elementk.
    • if same true, return k.
  • increase k 1.

source: http://es5.github.io/#x15.4.4.14

and yes, there no guarantees array structure - there nothing more efficient linear search.

i'm not sure how 1 makes formal proof absence of though.


Comments

Popular posts from this blog

twig - Using Twigbridge in a Laravel 5.1 Package -

jdbc - Not able to establish database connection in eclipse -

Kivy: Swiping (Carousel & ScreenManager) -