Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions Binary_search/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
BINARY ALGORITHM
This algorithm help the user to search a particular element present in an array(using the index of element present in an array)
**How the Algorithm Works**
1. Find the middle element
2. If middle element equal to searched value algorithm stops:
otherwise there are two cases:
2.1 search the value is less than that of the middle element.Here,
the algorithm go to the step 1 for the part of the array that before middle element
2.2 search the value is greater than that of the middle element.And here,
the algorithm go to the step 1 for the part of the array that after middle element
26 changes: 26 additions & 0 deletions Binary_search/main.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
#include <iostream>
using namespace std;
int binarySearch(int arr[], int l, int r, int x)
{
if (r >= l)
{
int mid = l + (r - l) / 2;
if (arr[mid] == x)
return mid;
if (arr[mid] > x)
return binarySearch(arr, l, mid - 1, x);
return binarySearch(arr, mid + 1, r, x);
}
return -1;
}

int main(void)
{
int arr[] = { 24, 33, 4, 130, 41 };
int x = 4;
int n = sizeof(arr) / sizeof(arr[0]);
int result = binarySearch(arr, 0, n - 1, x);
(result == -1) ? cout << "No such Element in array"
: cout << "Element is present at index " << result;
return 0;
}