-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
Binary_Search.cs
47 lines (42 loc) · 1.22 KB
/
Binary_Search.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
42
43
44
45
46
47
using System;
// The namespace refers to the project name you are working on.
namespace BinarySearch
{
class Program
{
public static int Binary_Search(int[] array, int size, int desired)
{
int left = 0, right = size - 1, middle;
while (left <= right)
{
middle = left + (right - left) / 2;
if (array[middle] == desired)
return middle;
else if (desired < array[middle])
right = middle - 1;
else
left = middle + 1;
}
return -1;
}
static void Main(string[] args)
{
int [] array = {1, 2, 3, 4, 5, 6, 7};
if (Binary_Search(array, 7, 4) != -1)
Console.WriteLine("Found");
else
Console.WriteLine("Not Found");
// Element 9 to be searched
if (Binary_Search(array, 7, 9) != -1)
Console.WriteLine("Found");
else
Console.WriteLine("Not Found");
Console.WriteLine();
Console.ReadLine(); // To hold output (optional)
}
}
}
/* Output
Found
Not Found
*/