Created
December 15, 2017 18:47
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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