-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathC18BinarySearchInArray.cpp
More file actions
42 lines (34 loc) · 1.01 KB
/
C18BinarySearchInArray.cpp
File metadata and controls
42 lines (34 loc) · 1.01 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
40
41
42
#include<iostream>
using namespace std;
int BinarySearch(int arr[] , int n , int key){
/* Used in Sorted Array */
int startPosition = 0;
int endPosition = n;
while(startPosition <= endPosition){
int midPosition = (startPosition + endPosition)/2; // store mid index
// cout<<midPosition<<endl;
if(arr[midPosition] == key){
return midPosition;
}
else if(arr[midPosition] < key){
startPosition = midPosition + 1;
}
else if(arr[midPosition] > key){
endPosition = midPosition - 1;
}
// cout<<startPosition<<endPosition<<endl;
}
return -1;
}
int main(){
// Binary Searching in Array
// find element in Index And Print its position
int n = 7;
int arr1[7] = { 1 , 2 , 5 , 11 , 13 , 45 , 99}; // Sorted Array
int e;
cout<<"Elements you want to Find : ";
cin>>e;
int l = BinarySearch(arr1 , n , e);
cout<<l;
return 0;
}