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 ofo
argumenttostring(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
.
- let elementk result of calling [[get]] internal method of o argument
- 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
Post a Comment