Skip to content

Instantly share code, notes, and snippets.

@andrewsouthard1
Last active June 28, 2022 20:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrewsouthard1/a3dacbddfe3f71742a2ef52874c93024 to your computer and use it in GitHub Desktop.
Save andrewsouthard1/a3dacbddfe3f71742a2ef52874c93024 to your computer and use it in GitHub Desktop.
Binary Search - Complete
def binary_search(n, arr)
middle = arr.length / 2
i = 0
j = arr.length - 1
while i < j
if arr[middle] == n
return true
elsif arr[middle] < n
i = middle + 1
middle = i + j / 2
else
j = middle - 1
middle = i + j / 2
end
end
false
end
@stephenbaidu
Copy link

There's a bug. middle = i + j / 2 should be middle = (i + j) / 2, with the parenthesis

And also, how about moving the middle = ... to the top like below:

def binary_search(n, arr)
  i = 0
  j = arr.length - 1

  while i < j
    middle = (j + i) / 2
    if arr[middle] == n
      return true
    elsif arr[middle] < n
      i = middle + 1
    else
      j = middle - 1
    end
  end
  false
end

@chrisconcepcion
Copy link

chrisconcepcion commented Jun 28, 2022

There's a bug. middle = i + j / 2 should be middle = (i + j) / 2, with the parenthesis

And also, how about moving the middle = ... to the top like below:

def binary_search(n, arr)
  i = 0
  j = arr.length - 1

  while i < j
    middle = (j + i) / 2
    if arr[middle] == n
      return true
    elsif arr[middle] < n
      i = middle + 1
    else
      j = middle - 1
    end
  end
  false
end

This is incorrect as well.

This is a working solution + simple tests

def binary_search(n, array)
        i = 0
        final_index = array.size - 1

        while i <= final_index
            # calculate middle
            middle = (i + final_index)/2
            if array[middle] == n
                return true
            elsif array[middle] < n
                i = middle + 1
            # when array[middle] > n
            else
                final_index = middle - 1
            end
        end
        false
    end

    # testing for finding all values
    array = [1,2,6,7,8,44,56]
    results = []
    i = 0
    while i < array.size
        results << binary_search(array[i], array)
        i = i + 1
    end

    # final test, testing for a non-available value
    results << binary_search(69, array)
    
    # we should get 7 true consequentively and a false at the end
    results == [true, true, true, true, true, true, true, false]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment