-
Notifications
You must be signed in to change notification settings - Fork 7.8k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #558 from aryankashyap7/BinarySearch
Added Binary Search Code in C++
- Loading branch information
Showing
2 changed files
with
41 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
39 changes: 39 additions & 0 deletions
39
Program's_Contributed_By_Contributors/C++ Programs/Binary_Search.cpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} |