Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created January 17, 2018 07:34
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/949f785c9d9785792d6f1108e47b7b84 to your computer and use it in GitHub Desktop.
Save jianminchen/949f785c9d9785792d6f1108e47b7b84 to your computer and use it in GitHub Desktop.
Modified binary search - find smallest index - need to evaluate the idea to find smallest index.
using System;
class Solution
{
public static int IndexEqualsValueSearch(int[] arr)
{
if (arr.Length == 0)
{
return -1;
}
var startIndex = 0;
var endIndex = arr.Length - 1;
var found = -1;
while(endIndex - startIndex >= 0)
{
var middle = startIndex + (endIndex - startIndex)/2;
if (arr[middle] == middle)
{
found = middle;
endIndex = middle - 1;
}
else if(arr[middle] < middle)
{
startIndex = middle + 1;
}
else
{
endIndex = middle - 1;
}
}
return found;
}
static void Main(string[] args)
{
Console.WriteLine(IndexEqualsValueSearch(new int[]{1, 2, 3, 7, 8, 9, 10}));
}
}
/*
[-8, 0, 2, 5] sorted distince arr[i] < arr[j], increment at least 1
[0, 1, 2, 3] always increment one.
[-8, -1, 0, 2] -> are you supposed to check that it is not descending?
return lowest index i
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment