Skip to content

Commit f5f1113

Browse files
committed
added searching algorithm
1 parent c1c3173 commit f5f1113

File tree

2 files changed

+80
-0
lines changed

2 files changed

+80
-0
lines changed

searching/binary_search.cpp

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
# include <iostream>
2+
# include <string>
3+
using namespace std;
4+
5+
int binarySearch(int arr[], int n, int key){
6+
// getting both end of the array
7+
int s = 0;
8+
int end = n;
9+
int mid;
10+
while(s<=end){
11+
// finding middle index of array
12+
mid = (s+end)/2;
13+
if(arr[mid]==key){
14+
//if key is found at middle
15+
return mid;
16+
}
17+
else if(key<arr[mid]){
18+
end = mid-1;
19+
}
20+
else{
21+
s=mid+1;
22+
}
23+
}
24+
//if key is not found in the array
25+
return -1;
26+
}
27+
28+
29+
int main(){
30+
int n, key,i;
31+
cout<<"Enter the size of array"<<endl;
32+
cin>>n;
33+
int arr[n];
34+
//input array
35+
//enter array in sorted manner
36+
for(i=0;i<n;i++){
37+
cin>>arr[i];
38+
}
39+
cout<<"Enter the key to search"<<endl;
40+
cin>>key;
41+
int index = binarySearch(arr, n, key);
42+
string result = (index==-1)? "Number not found": "Found at "+to_string(index)+ " position";
43+
cout<<result<<endl;
44+
return 0;
45+
}

searching/linear_search.cpp

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
# include <iostream>
2+
using namespace std;
3+
4+
int search(int arr2[], int n, int key){
5+
for(int i=0; i<n; i++){
6+
//comparing key to array values one by one
7+
if(arr2[i]==key){
8+
return i;
9+
}
10+
}
11+
//if number is not found
12+
return -1;
13+
}
14+
15+
16+
int main(){
17+
int n;
18+
cout<<"Enter the length of array"<<endl;
19+
cin>>n;
20+
int arr2[n];
21+
for(int i=0; i<n;i++){
22+
cin>>arr2[i];
23+
}
24+
int key;
25+
cout<<"Enter the key to find in the array"<<endl;
26+
cin>>key;
27+
int result = search(arr2, n, key);
28+
if(result==-1){
29+
cout<<"Number is not present"<<endl;
30+
}
31+
else{
32+
cout<<"Number is present at index "<<result<<endl;
33+
}
34+
return 0;
35+
}

0 commit comments

Comments
 (0)