You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/dsa/binary_search/binary-search.md
+56-1
Original file line number
Diff line number
Diff line change
@@ -4,4 +4,59 @@ title: Binary Search
4
4
sidebar_label: Binary Search
5
5
description: "In this blog post, we'll dive into the binary search algorithm, a fundamental technique in computer science for efficiently finding an element in a sorted array."
6
6
tags: [dsa, algorithms, binary search]
7
-
---
7
+
---
8
+
9
+
10
+
## Introduction
11
+
Binary search is a searching algorithm, used to search for an element in an array. It follows a unique approach which reduces the time complexity as compared to linear search. However, to use binary search, the array must be sorted.
12
+
13
+
## Implementation
14
+
15
+
Let us see how to implement binary search in Java:
16
+
17
+
```java
18
+
//let element to be found=target
19
+
int low=0;
20
+
int high=n-1; //where n is the length of the sorted array
21
+
int mid; //represents the mid index of the array
22
+
23
+
int flag=0; //element not yet found
24
+
25
+
while(low<=high) {
26
+
27
+
mid=(low + high)/2;
28
+
if(arr[mid]==target) {
29
+
flag=1; //element found
30
+
System.out.println("Target found!");
31
+
break;
32
+
}
33
+
elseif(arr[mid]<target) {
34
+
// which means target is to the right of mid element
35
+
low=mid+1;
36
+
}
37
+
else {
38
+
//target is to the left of mid element
39
+
high=mid-1;
40
+
}
41
+
42
+
}
43
+
44
+
if(flag==0) {
45
+
System.out.println("Target not found!");
46
+
}
47
+
```
48
+
49
+
In this algorithm, the searching interval of the array is divided into half at every iteration until the target is found. This results in lesser comparisions and decreases the time required.
0 commit comments