-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearchAlgorithm.cs
More file actions
49 lines (41 loc) · 1.32 KB
/
BinarySearchAlgorithm.cs
File metadata and controls
49 lines (41 loc) · 1.32 KB
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
48
49
using System;
namespace BinarySearchAlgorithm
{
public class BinarySearch
{
public int Binary_Search(int[] data, int itemToSearch)
{
//initialize the start and the end value
int start = 0;
int end = data.Length - 1;
while (start <= end)
{
int middle = (start + end) / 2;
if (data[middle] == itemToSearch)
{
return middle;
}
else if (data[middle] < itemToSearch)
{
start = middle + 1;
}
else
{
end = middle - 1;
}
}
return -1;
}
static void Main(string[] args)
{
Console.WriteLine(DateTime.Now);
int[] data = { 68, 6, 12, 18, 36, 71 };
BinarySearch result = new BinarySearch();
int itemToSearch = 36;
int index = result.Binary_Search(data, itemToSearch);
Console.WriteLine((index > 0) ? $"Item {itemToSearch} found at position {index}" : $"Item {itemToSearch} not found");
Console.WriteLine(DateTime.Now);
Console.ReadLine();
}
}
}