-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Expand file tree
/
Copy pathExercise_1.cs
More file actions
47 lines (44 loc) · 1.15 KB
/
Exercise_1.cs
File metadata and controls
47 lines (44 loc) · 1.15 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
// Time Complexity
// Best Case - O(1)
// Average Case - O(log n)
// Worst Case - O(log n)
// Space Complexity
// O(1)
public class BinarySearch
{
// Returns index of x if it is present in arr[l.. r], else return -1
public int binarySearch(int[] arr, int l, int r, int x)
{
//Write your code here
while (l <= r)
{
int mid = l + (r - l) / 2;
if (arr[mid] == x)
{
return mid;
}
else if (arr[mid] > x)
{
r = mid - 1;
}
else
{
l = mid + 1;
}
}
return -1;
}
// Driver method to test above
public static void Main(String[] args)
{
BinarySearch ob = new BinarySearch();
int[] arr = { 2, 3, 4, 10, 40 };
int n = arr.Length;
int x = 10;
int result = ob.binarySearch(arr, 0, n - 1, x);
if (result == -1)
Console.WriteLine("Element not present");
else
Console.WriteLine("Element found at index " + result);
}
}