From fc0ba822ea4b93ddb6f40138fcc77cc4d23ce379 Mon Sep 17 00:00:00 2001 From: Apoorva-Atre Date: Tue, 23 Jul 2024 13:01:24 +0530 Subject: [PATCH] Added content in binary-search.md in dsa under docs --- docs/dsa/binary_search/binary-search.md | 57 ++++++++++++++++++++++++- 1 file changed, 56 insertions(+), 1 deletion(-) diff --git a/docs/dsa/binary_search/binary-search.md b/docs/dsa/binary_search/binary-search.md index 9988b5705..fbc27804e 100644 --- a/docs/dsa/binary_search/binary-search.md +++ b/docs/dsa/binary_search/binary-search.md @@ -4,4 +4,59 @@ title: Binary Search sidebar_label: Binary Search 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." tags: [dsa, algorithms, binary search] ---- \ No newline at end of file +--- + + +## Introduction +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. + +## Implementation + +Let us see how to implement binary search in Java: + +```java + //let element to be found=target + int low=0; + int high=n-1; //where n is the length of the sorted array + int mid; //represents the mid index of the array + + int flag=0; //element not yet found + + while(low<=high) { + + mid=(low + high)/2; + if(arr[mid]==target) { + flag=1; //element found + System.out.println("Target found!"); + break; + } + else if(arr[mid] +Binary search : O(log n) + +## Points to Remember: + +- Binary search requires a sorted array. +- Works for 1 dimensional arrays. +- Faster and complex than sequential search. +- Uses the divide and conquer approach. +- Best if arrays are too long (large datasets).