Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created September 15, 2017 23:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jianminchen/f76aca7eb32a2399d2618fe2aafbd667 to your computer and use it in GitHub Desktop.
Save jianminchen/f76aca7eb32a2399d2618fe2aafbd667 to your computer and use it in GitHub Desktop.
Modified binary search - 30 minutes practice - I got advise to work on middle instead of start, the binary search is to search the middle.
using System;
class Solution
{
public static int IndexEqualsValueSearch(int[] arr)
{
// your code goes here
if(arr == null || arr.Length == 0)
{
return -1;
}
// assume that array is not empty
var start = 0;
var end = arr.Length - 1;
while(start <= end)
{
var middle = start + (end - start)/ 2;
var middleValue = arr[middle] - middle;
bool found = middleValue == 0;
if(found)
{
return middle;
}
if(middleValue < 0)
{
start = middle + 1;
}
else // > 0
{
end = middle - 1;
}
}
return -1;
}
static void Main(string[] args)
{
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment