Created
November 20, 2019 03:27
-
-
Save aabir/409a6b0ca3710a17ddb07fc9e047f908 to your computer and use it in GitHub Desktop.
BinarySearch in C#
This file contains hidden or 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; | |
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