Skip to content

Commit 489f7fa

Browse files
authored
Merge pull request #3801 from Apoorva-Atre/mybranch
Added content in binary-search.md in dsa under docs
2 parents 985ac2f + fc0ba82 commit 489f7fa

File tree

1 file changed

+56
-1
lines changed

1 file changed

+56
-1
lines changed

docs/dsa/binary_search/binary-search.md

+56-1
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,59 @@ title: Binary Search
44
sidebar_label: Binary Search
55
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."
66
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+
else if(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.
50+
51+
## Time complexity:
52+
53+
Linear/Sequential search: O(n)<br />
54+
Binary search : O(log n)
55+
56+
## Points to Remember:
57+
58+
- Binary search requires a sorted array.
59+
- Works for 1 dimensional arrays.
60+
- Faster and complex than sequential search.
61+
- Uses the divide and conquer approach.
62+
- Best if arrays are too long (large datasets).

0 commit comments

Comments
 (0)