forked from iiitv/algos
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BinarySearch.cs
41 lines (39 loc) · 905 Bytes
/
BinarySearch.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
using System;
public class BinarySearch
{
public static void Main()
{
int[] data = new int[] {1, 5, 6, 8, 13, 45, 65, 121, 123, 163, 245, 334};
int target = 123;
int index = Search(data, target);
if(index >= 0)
{
Console.WriteLine("Index of target: " + index);
}
else
{
Console.WriteLine("Not found\n");
}
}
public static int Search(int[] data, int target)
{
int left = 0, right = data.Length;
while(left <= right)
{
int mid = (left + right) / 2;
if (data[mid] == target)
{
return mid;
}
if (data[mid] < target)
{
left = mid + 1;
}
else
{
right = mid - 1;
}
}
return -1;
}
}