browser/devtools/debugger/test/code_binary_search.coffee

changeset 0
6474c204b198
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/browser/devtools/debugger/test/code_binary_search.coffee	Wed Dec 31 06:09:35 2014 +0100
     1.3 @@ -0,0 +1,18 @@
     1.4 +# Uses a binary search algorithm to locate a value in the specified array.
     1.5 +window.binary_search = (items, value) ->
     1.6 +
     1.7 +  start = 0
     1.8 +  stop  = items.length - 1
     1.9 +  pivot = Math.floor (start + stop) / 2
    1.10 +
    1.11 +  while items[pivot] isnt value and start < stop
    1.12 +
    1.13 +    # Adjust the search area.
    1.14 +    stop  = pivot - 1 if value < items[pivot]
    1.15 +    start = pivot + 1 if value > items[pivot]
    1.16 +
    1.17 +    # Recalculate the pivot.
    1.18 +    pivot = Math.floor (stop + start) / 2
    1.19 +
    1.20 +  # Make sure we've found the correct value.
    1.21 +  if items[pivot] is value then pivot else -1
    1.22 \ No newline at end of file

mercurial