Created
September 15, 2017 23:36
-
-
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.
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