Skip to content

Commit

Permalink
binary search
Browse files Browse the repository at this point in the history
  • Loading branch information
no0ne committed Dec 24, 2023
1 parent e176192 commit 563ad6a
Show file tree
Hide file tree
Showing 19 changed files with 843 additions and 28 deletions.
4 changes: 2 additions & 2 deletions basic/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
<meta name="twitter:description" content=""/>
<meta name="twitter:site" content="@_su__mit___"/>
<meta name="application-name" content="Sumit&#39;s Blog">
<meta name="apple-mobile-web-app-title" content="Sumit&#39;s Blog"><meta name="theme-color" content="#ffffff"><meta name="msapplication-TileColor" content="#da532c"><link rel="icon" href="/images/logo.png"><link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png"><link rel="mask-icon" href="/safari-pinned-tab.svg" color="#5bbad5"><link rel="manifest" href="/site.webmanifest"><link rel="canonical" href="https://sumit2011.github.io/basic/" /><link rel="prev" href="https://sumit2011.github.io/binary-search/" /><link rel="next" href="https://sumit2011.github.io/upload-vulnerabilities/" /><link rel="stylesheet" href="/lib/normalize/normalize.min.css"><link rel="stylesheet" href="/css/style.min.css"><link rel="stylesheet" href="/lib/fontawesome-free/all.min.css"><link rel="stylesheet" href="/lib/animate/animate.min.css"><script type="application/ld+json">
<meta name="apple-mobile-web-app-title" content="Sumit&#39;s Blog"><meta name="theme-color" content="#ffffff"><meta name="msapplication-TileColor" content="#da532c"><link rel="icon" href="/images/logo.png"><link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png"><link rel="mask-icon" href="/safari-pinned-tab.svg" color="#5bbad5"><link rel="manifest" href="/site.webmanifest"><link rel="canonical" href="https://sumit2011.github.io/basic/" /><link rel="prev" href="https://sumit2011.github.io/binary_search/" /><link rel="next" href="https://sumit2011.github.io/upload-vulnerabilities/" /><link rel="stylesheet" href="/lib/normalize/normalize.min.css"><link rel="stylesheet" href="/css/style.min.css"><link rel="stylesheet" href="/lib/fontawesome-free/all.min.css"><link rel="stylesheet" href="/lib/animate/animate.min.css"><script type="application/ld+json">
{
"@context": "http://schema.org",
"@type": "BlogPosting",
Expand Down Expand Up @@ -139,7 +139,7 @@ <h2 class="toc-title">Contents</h2>
</section>
</div>

<div class="post-nav"><a href="/binary-search/" class="prev" rel="prev" title="Binary Search"><i class="fas fa-angle-left fa-fw" aria-hidden="true"></i>Binary Search</a>
<div class="post-nav"><a href="/binary_search/" class="prev" rel="prev" title="Binary Search"><i class="fas fa-angle-left fa-fw" aria-hidden="true"></i>Binary Search</a>
<a href="/upload-vulnerabilities/" class="next" rel="next" title="Upload Vulnerabilities">Upload Vulnerabilities<i class="fas fa-angle-right fa-fw" aria-hidden="true"></i></a></div>
</div>
</article></div>
Expand Down
578 changes: 578 additions & 0 deletions binary_search/index.html

Large diffs are not rendered by default.

237 changes: 237 additions & 0 deletions binary_search/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,237 @@
# Binary Search



<!--more-->

{{< admonition type=note title="Note" open=true >}}
_Use the table of contents to navigate to the portion that you are interested in._
{{< /admonition >}}

## Introduction
We know that there is two type of searching technique `1.Linear Search` and `2.Binary Search`. Here we discus only about binary search.
***Binary search*** is a searching technique, it is used to locate a specific element with in the ***sorted array***.
>It is applicable only on monotonic function which means values should be in the **increasing** or **decreasing** order.
## Creation of Function
<!-- The given code snippet implements the binary search algorithm for finding a specific integer key within a sorted integer array 'arr'. It initializes 'start' and 'end' indices to the first and last elements of the array, respectively, and calculates the middle index 'mid'. Inside a while loop that continues as long as the 'start' index is less than or equal to the 'end' index, the code compares the value at index 'mid' with the given 'key'. If 'key' matches the element at 'mid', the function returns 'mid' as the index where 'key' is found. If 'key' is greater than the element at 'mid', the 'start' index is updated to 'mid + 1', effectively narrowing the search range to the right half. If 'key' is smaller, the 'end' index is updated to 'mid - 1', narrowing the search range to the left half. After each update to 'start' or 'end', 'mid' is recalculated as the average of 'start' and 'end'. If the loop concludes without finding 'key', the function returns -1 to indicate that the key is not present in the array. This binary search algorithm's efficiency lies in its ability to halve the search range with each iteration, resulting in a time complexity of O(log n), making it efficient for searching in large sorted arrays. -->


first initialise `start` and `end` indices to the first and last element of the array respectively. then calculate the middle index by `(start+end)/2`.
Inside the while loop, compare the value of mid with the key until the start index becomes less than or equal to the end index. if key matches with the mid element it returns the mid element. If if key is greater than the mid element the start index will updated to the mid+1.
```c++
#include<iostream>
using namespace std;

int binarysearch(int arr[], int size, int key)
{
int start =0;
int end = size-1;
//int mid= (start+end)/2;
int mid= start + (end-start)/2;
while(start <= end){
if(arr[mid] == key){
return mid;
}
if(key> arr[mid]){ //go to right part
start= mid +1 ;
}
else{
end= mid - 1; //go to left part
}
//mid= (start+end)/2;
mid = start + (end-start)/2;
}
return -1;
}
```
## The Main Function
```c++
int main()
{
int even[6]= {2,4,6,8,12,18};
int odd[5]= {3,8,11,14,16};
int evenindex= binarysearch(even, 6, 6);
cout<<"index of 6 is "<<evenindex << endl;
int oddindex= binarysearch(odd, 5, 14);
cout<<"index of 14 is "<<oddindex << endl;
return 0;
}
```
### Output
{{< figure src="/posts/DSA/binary_search/output.png" >}}

{{< admonition type=tip title="Complete Code" open=false >}}

```c++
#include<iostream>
//it applicable only on monotonic function values should be in inc or dec order.
using namespace std;
int binarysearch(int arr[], int size, int key)
{
int start =0;
int end = size-1;
//int mid= (start+end)/2;
int mid= start + (end-start)/2;
while(start <= end){
if(arr[mid] == key){
return mid;
}
//go to right part
if(key> arr[mid]){
start= mid +1 ;
}
else{
end= mid - 1;
}
//mid= (start+end)/2;
mid = start + (end-start)/2;
}
return -1;
}

int main(){
int even[6]= {2,4,6,8,12,18};
int odd[5]= {3,8,11,14,16};
int evenindex= binarysearch(even, 6, 6);
cout<<"index of 6 is "<<evenindex << endl;
int oddindex= binarysearch(odd, 5, 14);
cout<<"index of 14 is "<<oddindex << endl;
return 0;
}
```
{{< /admonition >}}
### Time Complexity:
Best Case: O(1)
Average Case: O(log N)
Worst Case: O(log N)
### Space Complexicity
Space Complexicity: O(1)
## Advantages:
* faster than linear search
* More efficient
* Minimal memory requirement
* Easy to understand and implement
* More efficient for large dataset
## Drawbacks:
* The array should be sorted.
* Not suitable for unordered lists
* Inefficient for small dataset
* Not adaptive for changes
* Limited to static dataset
## Applications:
* Database searching
* Finding elements in a array
* Used in file system to search a specific file
* In machine learning
* In Game development
{{< admonition type=question title="Problems" open=false >}}
{{< link "https://www.codingninjas.com/studio/problems/first-and-last-position-of-an-element-in-sorted-array_1082549?interviewProblemRedirection=true" "**First and Last position of an Element in Sorted Array** (Coding Ninja)" >}}
{{< /admonition >}}
### First and Last position of an element in sorted array solution
```c++
// pair <int, int> p;
// p.first = 5;
// p.second = 6;
#include<iostream>
using namespace std;
int firstOccurance(int arr[], int n, int key){
int start = 0;
int end = n-1;
int mid = start +(end-start)/2;
int ans = -1;
while(start <= end)
{
if (arr[mid]== key)
{
ans = mid;
end = mid - 1;
}
else if (arr[mid] < key)
{ // go to right part
start = mid + 1;
}
else if (arr[mid] > key)
{ // go to left part
end = mid -1;
}
mid = start + (end - start)/2;
}
return ans;
}
int lastOccurance(int arr[], int n, int key){
int start = 0;
int end = n-1;
int mid = start +(end-start)/2;
int ans = -1;
while(start <= end)
{
if (arr[mid]== key)
{
ans = mid;
start = mid + 1;
}
else if (arr[mid] < key)
{ // go to right part
start = mid + 1;
}
else if (arr[mid] > key)
{ // go to left part
end = mid -1;
}
mid = start + (end - start)/2;
}
return ans;
}
pair<int , int> firstAndLastOccurance(int arr[], int n, int key){
pair<int , int > p;
p.first = firstOccurance(arr , n, key);
p.second = lastOccurance(arr , n , key);
return p;
}
int main() {
int arr[9]={1,2,3,3,3,3,3,4,5};
cout << " first occurace of 3 is index " << firstOccurance(arr, 9 , 3) << endl;
cout << " last occurace of 3 is index " << lastOccurance(arr, 9 , 3) << endl;
firstAndLastOccurance(arr, 9, 3);
}
```






{{< admonition type=tip title="Fun Dose" open=false >}}
{{< youtube FMzj9UYHTPQ >}}
{{< /admonition >}}


Binary file added binary_search/output.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added binary_search/photo.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 1 addition & 1 deletion categories/dsa/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@
<a href="/oops/" class="archive-item-link">Oops(object oriented programming)</a>
<span class="archive-item-date">15-02</span>
</article><article class="archive-item">
<a href="/binary-search/" class="archive-item-link">Binary Search</a>
<a href="/binary_search/" class="archive-item-link">Binary Search</a>
<span class="archive-item-date">30-01</span>
</article><article class="archive-item">
<a href="/binary-tree/" class="archive-item-link">Binary Tree</a>
Expand Down
4 changes: 2 additions & 2 deletions categories/dsa/index.xml
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,10 @@
</item>
<item>
<title>Binary Search</title>
<link>https://sumit2011.github.io/binary-search/</link>
<link>https://sumit2011.github.io/binary_search/</link>
<pubDate>Mon, 30 Jan 2023 11:54:28 &#43;0530</pubDate>
<author>Sumit</author>
<guid>https://sumit2011.github.io/binary-search/</guid>
<guid>https://sumit2011.github.io/binary_search/</guid>
<description><![CDATA[<div class="featured-image">
<img src="/photo.png" referrerpolicy="no-referrer">
</div>]]></description>
Expand Down
2 changes: 1 addition & 1 deletion categories/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ <h3 class="card-item-title">
</article><article class="archive-item">
<a href="/basic/" class="archive-item-link">Datatypes Variable and Operators</a>
</article><article class="archive-item">
<a href="/binary-search/" class="archive-item-link">Binary Search</a>
<a href="/binary_search/" class="archive-item-link">Binary Search</a>
</article><span class="more-post">
<a href="/categories/dsa/" class="more-single-link">More >></a>
</span></div>
Expand Down
14 changes: 7 additions & 7 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -180,19 +180,19 @@
<a href="/basic/">Read More</a><div class="post-tags">
<i class="fas fa-tags fa-fw" aria-hidden="true"></i>&nbsp;<a href="/tags/c/">C</a>,&nbsp;<a href="/tags/c&#43;&#43;/">C&#43;&#43;</a></div></div>
</article><article class="single summary" itemscope itemtype="http://schema.org/Article"><div class="featured-image-preview">
<a href="/binary-search/"><img
<a href="/binary_search/"><img
class="lazyload"
src="/svg/loading.min.svg"
data-src="/binary-search/photo.png"
data-srcset="/binary-search/photo.png, /binary-search/photo.png 1.5x, /binary-search/photo.png 2x"
data-src="/binary_search/photo.png"
data-srcset="/binary_search/photo.png, /binary_search/photo.png 1.5x, /binary_search/photo.png 2x"
data-sizes="auto"
alt="/binary-search/photo.png"
title="/binary-search/photo.png" width="1111" height="331" /></a>
alt="/binary_search/photo.png"
title="/binary_search/photo.png" width="1111" height="331" /></a>
</div><h1 class="single-title" itemprop="name headline">
<a href="/binary-search/">Binary Search</a>
<a href="/binary_search/">Binary Search</a>
</h1><div class="post-meta"><span class="post-author"><a href="/about/" title="Author" rel=" author" class="author"><i class="fas fa-user-circle fa-fw" aria-hidden="true"></i>Sumit</a>
</span>&nbsp;<span class="post-publish">published on <time datetime="30-01-2023">30-01-2023</time></span>&nbsp;<span class="post-category">included in <a href="/categories/dsa/"><i class="far fa-folder fa-fw" aria-hidden="true"></i>DSA</a></span></div><div class="content"></div><div class="post-footer">
<a href="/binary-search/">Read More</a><div class="post-tags">
<a href="/binary_search/">Read More</a><div class="post-tags">
<i class="fas fa-tags fa-fw" aria-hidden="true"></i>&nbsp;<a href="/tags/c/">C</a>,&nbsp;<a href="/tags/c&#43;&#43;/">C&#43;&#43;</a></div></div>
</article><article class="single summary" itemscope itemtype="http://schema.org/Article"><div class="featured-image-preview">
<a href="/oops/"><img
Expand Down
2 changes: 1 addition & 1 deletion index.json

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions index.xml
Original file line number Diff line number Diff line change
Expand Up @@ -68,10 +68,10 @@
</item>
<item>
<title>Binary Search</title>
<link>https://sumit2011.github.io/binary-search/</link>
<link>https://sumit2011.github.io/binary_search/</link>
<pubDate>Mon, 30 Jan 2023 11:54:28 &#43;0530</pubDate>
<author>Sumit</author>
<guid>https://sumit2011.github.io/binary-search/</guid>
<guid>https://sumit2011.github.io/binary_search/</guid>
<description><![CDATA[<div class="featured-image">
<img src="/photo.png" referrerpolicy="no-referrer">
</div>]]></description>
Expand Down
4 changes: 2 additions & 2 deletions oops/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
<meta name="twitter:description" content=""/>
<meta name="twitter:site" content="@_su__mit___"/>
<meta name="application-name" content="Sumit&#39;s Blog">
<meta name="apple-mobile-web-app-title" content="Sumit&#39;s Blog"><meta name="theme-color" content="#ffffff"><meta name="msapplication-TileColor" content="#da532c"><link rel="icon" href="/images/logo.png"><link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png"><link rel="mask-icon" href="/safari-pinned-tab.svg" color="#5bbad5"><link rel="manifest" href="/site.webmanifest"><link rel="canonical" href="https://sumit2011.github.io/oops/" /><link rel="next" href="https://sumit2011.github.io/binary-search/" /><link rel="stylesheet" href="/lib/normalize/normalize.min.css"><link rel="stylesheet" href="/css/style.min.css"><link rel="stylesheet" href="/lib/fontawesome-free/all.min.css"><link rel="stylesheet" href="/lib/animate/animate.min.css"><script type="application/ld+json">
<meta name="apple-mobile-web-app-title" content="Sumit&#39;s Blog"><meta name="theme-color" content="#ffffff"><meta name="msapplication-TileColor" content="#da532c"><link rel="icon" href="/images/logo.png"><link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png"><link rel="mask-icon" href="/safari-pinned-tab.svg" color="#5bbad5"><link rel="manifest" href="/site.webmanifest"><link rel="canonical" href="https://sumit2011.github.io/oops/" /><link rel="next" href="https://sumit2011.github.io/binary_search/" /><link rel="stylesheet" href="/lib/normalize/normalize.min.css"><link rel="stylesheet" href="/css/style.min.css"><link rel="stylesheet" href="/lib/fontawesome-free/all.min.css"><link rel="stylesheet" href="/lib/animate/animate.min.css"><script type="application/ld+json">
{
"@context": "http://schema.org",
"@type": "BlogPosting",
Expand Down Expand Up @@ -213,7 +213,7 @@ <h2 id="inheritance">Inheritance</h2>
</div>

<div class="post-nav">
<a href="/binary-search/" class="next" rel="next" title="Binary Search">Binary Search<i class="fas fa-angle-right fa-fw" aria-hidden="true"></i></a></div>
<a href="/binary_search/" class="next" rel="next" title="Binary Search">Binary Search<i class="fas fa-angle-right fa-fw" aria-hidden="true"></i></a></div>
</div>
</article></div>
</main><footer class="footer">
Expand Down
2 changes: 1 addition & 1 deletion posts/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@
<a href="/oops/" class="archive-item-link">Oops(object oriented programming)</a>
<span class="archive-item-date">15-02</span>
</article><article class="archive-item">
<a href="/binary-search/" class="archive-item-link">Binary Search</a>
<a href="/binary_search/" class="archive-item-link">Binary Search</a>
<span class="archive-item-date">30-01</span>
</article><article class="archive-item">
<a href="/binary-tree/" class="archive-item-link">Binary Tree</a>
Expand Down
4 changes: 2 additions & 2 deletions posts/index.xml
Original file line number Diff line number Diff line change
Expand Up @@ -66,10 +66,10 @@
</item>
<item>
<title>Binary Search</title>
<link>https://sumit2011.github.io/binary-search/</link>
<link>https://sumit2011.github.io/binary_search/</link>
<pubDate>Mon, 30 Jan 2023 11:54:28 &#43;0530</pubDate>
<author>Sumit</author>
<guid>https://sumit2011.github.io/binary-search/</guid>
<guid>https://sumit2011.github.io/binary_search/</guid>
<description><![CDATA[<div class="featured-image">
<img src="/photo.png" referrerpolicy="no-referrer">
</div>]]></description>
Expand Down
2 changes: 1 addition & 1 deletion sitemap.xml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
<loc>https://sumit2011.github.io/jr-penetration-tester/</loc><lastmod>2023-10-03T18:37:31&#43;05:30</lastmod><changefreq>weekly</changefreq><priority>0.5</priority></url><url>
<loc>https://sumit2011.github.io/upload-vulnerabilities/</loc><lastmod>2023-10-03T18:37:31&#43;05:30</lastmod><changefreq>weekly</changefreq><priority>0.5</priority></url><url>
<loc>https://sumit2011.github.io/basic/</loc><lastmod>2023-12-22T11:54:28&#43;05:30</lastmod><changefreq>weekly</changefreq><priority>1</priority></url><url>
<loc>https://sumit2011.github.io/binary-search/</loc><lastmod>2023-10-03T18:37:31&#43;05:30</lastmod><changefreq>weekly</changefreq><priority>0.5</priority></url><url>
<loc>https://sumit2011.github.io/binary_search/</loc><lastmod>2023-01-30T11:54:28&#43;05:30</lastmod><changefreq>weekly</changefreq><priority>0.5</priority></url><url>
<loc>https://sumit2011.github.io/oops/</loc><lastmod>2023-10-03T18:37:31&#43;05:30</lastmod><changefreq>weekly</changefreq><priority>0.5</priority></url><url>
<loc>https://sumit2011.github.io/tags/c/</loc><lastmod>2023-12-22T11:54:28&#43;05:30</lastmod><changefreq>weekly</changefreq><priority>1</priority></url><url>
<loc>https://sumit2011.github.io/tags/c&#43;&#43;/</loc><lastmod>2023-12-22T11:54:28&#43;05:30</lastmod><changefreq>weekly</changefreq><priority>1</priority></url><url>
Expand Down
2 changes: 1 addition & 1 deletion tags/c++/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@
<a href="/oops/" class="archive-item-link">Oops(object oriented programming)</a>
<span class="archive-item-date">15-02</span>
</article><article class="archive-item">
<a href="/binary-search/" class="archive-item-link">Binary Search</a>
<a href="/binary_search/" class="archive-item-link">Binary Search</a>
<span class="archive-item-date">30-01</span>
</article><article class="archive-item">
<a href="/binary-tree/" class="archive-item-link">Binary Tree</a>
Expand Down
Loading

0 comments on commit 563ad6a

Please sign in to comment.