Skip to content

Commit

Permalink
Merge pull request #558 from aryankashyap7/BinarySearch
Browse files Browse the repository at this point in the history
Added Binary Search Code in C++
  • Loading branch information
fineanmol authored Oct 5, 2021
2 parents 6f325bc + 2bf38b4 commit 4f331b9
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
2 changes: 2 additions & 0 deletions Contributors.html
Original file line number Diff line number Diff line change
Expand Up @@ -573,8 +573,10 @@ <h1 class="animated rubberBand delay-4s">Contributors</h1>

<a class="box-item" href="https://github.com/mofazil17"><span>Mohamed Fazil</span></a>
<a class="box-item" href="https://github.com/Tejaswi-Kumar"><span>Tejaswi Kumar</span></a>

<a class="box-item" href="https://github.com/TahuTech"><span>Nur Ali Sholikhin</span></a>
<a class="box-item" href="https://github.com/JuniorXcoder"><span>JuniorXcoder</span></a>
<a class="box-item" href="https://github.com/aryankashyap7"><span>Aryan Kashyap</span></a>



Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
// This code is to implement Binary Search in C++

// Here elements[] refers to the array of elements in sorted order and searchkey refers to the key element we are searching

#include <bits/stdc++.h>
using namespace std;

int binarySearch(int elements[], int searchkey, int low, int high)
{

while (low <= high)
{
int mid = low + (high - low) / 2;

if (elements[mid] == searchkey)
return mid;

if (elements[mid] < searchkey)
low = mid + 1;

else
high = mid - 1;
}

return -1;
}

int main(void)
{
int elements[] = {-3, 5, 7, 12, 45, 72, 430};
int searchkey = 7;
int n = sizeof(elements) / sizeof(elements[0]);
int result = binarySearch(elements, searchkey, 0, n - 1);
if (result == -1)
cout << "Element Not found";
else
cout << "Element is found at index " << result;
return 0;
}

0 comments on commit 4f331b9

Please sign in to comment.