Skip to content

Instantly share code, notes, and snippets.

@aabir
Created November 20, 2019 03:27
Show Gist options
  • Save aabir/409a6b0ca3710a17ddb07fc9e047f908 to your computer and use it in GitHub Desktop.
Save aabir/409a6b0ca3710a17ddb07fc9e047f908 to your computer and use it in GitHub Desktop.
BinarySearch in C#
using System;
namespace BinarySearch
{
class Program
{
static void Main(string[] args)
{
int[] inputArray = new int[4] { 10, 11, 12, 13 };
int key = 12;
Console.WriteLine(BinarySearch(inputArray, key));
Console.ReadLine();
}
public static object BinarySearch(int[] inputArray, int key)
{
int minIndex = 0;
int maxIndex = inputArray.Length;
while (minIndex < maxIndex)
{
int midIndex = (minIndex + maxIndex) / 2;
if (inputArray[midIndex] == key)
{
return midIndex;
}
else if (inputArray[minIndex] < key)
{
minIndex = midIndex + 1;
}
else
{
maxIndex = midIndex - 1;
}
}
return null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment