Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created December 15, 2017 18:47
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/fd1962e2b50fafb1f7d3cbdc69787d8a to your computer and use it in GitHub Desktop.
Save jianminchen/fd1962e2b50fafb1f7d3cbdc69787d8a to your computer and use it in GitHub Desktop.
Sept 14 2017 practice - the code has issue, the smallest index is not handled, for example, the array with [0, 1, 2, 3, 4], return index should be 0, not 2.
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