-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinarysearch.cpp
More file actions
39 lines (38 loc) · 1.38 KB
/
Copy pathbinarysearch.cpp
File metadata and controls
39 lines (38 loc) · 1.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
//find the index of given element using binary search
//usage binary search algorithm
//find key element index in an array using function
#include <iostream>
using namespace std;
int binarysearch(int arr[], int n,int key) //declaring function to contain binary search algorithm
{
int max = n-1; //max index of array is size -1
int min = 0; //minimum index of array is 0
int mid;
while ( min<= max)
{
mid = (min+max)/2; //mid index of array is half the sum of min + max index
if (arr[mid] == key)
return mid; //condition to return mid index if the key element is at the mid itself
if (arr[mid] < key)
min = mid + 1; //condition to shift to the right index if mid element is less than key element i.e the array being in ascending order
else if(arr[mid] > key)
max = mid - 1; //condition to shift to the left side of the array if key is smaller than the required array
}
return mid; //returning answer for the index of key element
}
int main()
{
int key;
int n;
cout<<"Enter size of array: ";
cin>>n;
int arr[n];
cout<<"Enter array elements: ";
for(int i=0;i<n;i++)
{
cin>>arr[i]; //taking input array separated by space
}
cout<<"Enter element to search: ";
cin>>key;
cout<<"Index of key element : "<<binarysearch(arr,n,key)<<endl;//calling function
}