-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathBinarySearch.linq
68 lines (46 loc) · 1.6 KB
/
BinarySearch.linq
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<Query Kind="Program" />
void Main()
{
int[] list_sorted = {1,2,3,4,5,6,7,8,9,10};
Console.WriteLine(BinarySearchAlgorithm(list_sorted,0));
}
// You can define other methods, fields, classes and namespaces here
/*
3. Binary Search
Note: Binary search requires the array to be sorted otherwise binary search
cannot be applied.
- Binary Search also works in the same way. When we want to search some
key value in a sorted list. We go to the middle point from the sorted list and
start comparing with the desired value. If the desired value is equal to the
middle value then we are done. If the value is greater than the middle value
then we reject the first half. If the value is less than the middle value then
we reject the second half. At each comparison, we are reducing our search
space by half.
- Time Complexity: O(logn). We always take half input and throw out the
other half. So the recurrence relation for binary search is T(n) = T(n/2) + c.
Using master theorem (divide and conquer), we get T(n) = O(logn)
- Space Complexity: O(1)
*/
bool BinarySearchAlgorithm(int[] list, int target)
{
int left = 0; // first index of the list
int right = list.Length - 1; //last index of the list
int mid;
while (left <= right)
{
mid = (left + right) / 2; // middle index of the list
if (list[mid] == target)
{
return true;
}
else if (target < list[mid])
{
right = mid - 1; //move the right pointer to the middle of the list
}
else
{
left = mid + 1; //move the left pointer to the middle of the list
}
}
return false;
}