-
Notifications
You must be signed in to change notification settings - Fork 0
/
binarySearch2.cpp
54 lines (43 loc) · 982 Bytes
/
binarySearch2.cpp
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
43
44
45
46
47
48
49
50
51
52
53
54
#include<iostream>
using namespace std;
int main(){
int arr[100];
int n;
cout<<"Enter size of the array"<<endl;
cin>>n;
cout<<"Enter elements in the array"<<endl;
for(int i=0;i<n;i++){
cin>>arr[i];
}
int start=0,end=n-1,ans=n,mid,target;
cout<<"enter element to be inserted or searched in the array"<<endl;
cin>>target;
while(start<=end){
mid=(start+end)/2;
if(arr[mid]==target){
ans=mid;
break;
}
else if(arr[mid]<target){
start=mid+1;
}
else{
ans= mid;
end=mid-1;
}
}
if(ans == n || arr[ans]!=target){
for(int i=n;i>ans;i--){
arr[i]=arr[i-1];
}
arr[ans]=target;
n++;
}
else{
cout<<"element already exist in the array at index "<<ans;
cout<<endl;
}
for(int i=0;i<n;i++){
cout<<" "<<arr[i]<<" ";
}
}