Skip to content

Instantly share code, notes, and snippets.

@aloisdg
Created September 30, 2018 11:20
Show Gist options
  • Save aloisdg/38ff759ea593b8d3a3d68459690dc062 to your computer and use it in GitHub Desktop.
Save aloisdg/38ff759ea593b8d3a3d68459690dc062 to your computer and use it in GitHub Desktop.
using System;
using System.Linq;
public class Program
{
public static bool Contains(int[] ints, int k)
{
if (ints.Length == 0)
return false;
if (ints.Length == 1)
return k == ints[0];
var position = ints.Length / 2;
var middle = ints[position];
if (k == middle)
return true;
// for perf we might want to use resize, copy or ArraySegment
var scope = k > middle ? ints.Skip(position) : ints.Take(position);
return Contains(scope.ToArray(), k);
}
public static bool Exists(int[] ints, int k)
{
return Contains(ints, k);
}
public static void Main()
{
Console.WriteLine(Exists(new int[]{},1) == false);
Console.WriteLine(Exists(new int[]{0},1) == false);
Console.WriteLine(Exists(new int[]{1},1) == true);
Console.WriteLine(Exists(new int[]{0,1},1) == true);
Console.WriteLine(Exists(new int[]{0,1},0) == true);
Console.WriteLine(Exists(new int[]{0,2},1) == false);
Console.WriteLine(Exists(new int[]{0,1,2},1) == true);
Console.WriteLine(Exists(new int[]{0,1,2},2) == true);
Console.WriteLine(Exists(new int[]{0,1,2,4},2) == true);
Console.WriteLine(Exists(new int[]{0,1,2,3,4},4) == true);
Console.WriteLine(Exists(new int[]{0,1,2,3,102},102) == true);
Console.WriteLine(Exists(new int[]{0,1,2,3,102,102,102,102,102},102) == true);
}
}
@aloisdg
Copy link
Author

aloisdg commented Sep 30, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment