Skip to content

Commit 1e810be

Browse files
committed
Algorithms for searching are added here, implemented in cpp language.
1 parent c1a783f commit 1e810be

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed

searching/binary.cpp

+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
#include <iostream>
2+
using namespace std;
3+
4+
int binarySearch(int arr[], int l, int r, int x)
5+
{
6+
if (r >= l)
7+
{
8+
int mid = l + (r - l)/2;
9+
10+
// If the element is present at the middle
11+
// itself
12+
if (arr[mid] == x)
13+
return mid;
14+
15+
// If element is smaller than mid, then
16+
// it can only be present in left subarray
17+
if (arr[mid] > x)
18+
return binarySearch(arr, l, mid-1, x);
19+
20+
// Else the element can only be present
21+
// in right subarray
22+
return binarySearch(arr, mid+1, r, x);
23+
}
24+
25+
// We reach here when element is not
26+
// present in array
27+
return -1;
28+
}
29+
30+
int main(void)
31+
{
32+
int arr[] = {2, 3, 4, 10, 40};
33+
int n = sizeof(arr)/ sizeof(arr[0]);
34+
int x = 10;
35+
int result = binarySearch(arr, 0, n-1, x);
36+
(result == -1)? cout<< "Element is not present in array\n"
37+
: cout<< "Element is present at index "<< result;
38+
return 0;
39+
}

searching/linear.cpp

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
#include<iostream>
2+
using namespace std;
3+
4+
int search(int arr[], int n, int x)
5+
{
6+
int i;
7+
for (i = 0; i < n; i++)
8+
if (arr[i] == x)
9+
return i;
10+
return -1;
11+
}
12+
int main()
13+
{
14+
int n, x;
15+
cout<<"size of the array\n";
16+
cin>>n;
17+
int arr[n];
18+
cout<<"value to bea searched\n";
19+
cin>>x;
20+
cout<<search(arr[],n,x);
21+
}

0 commit comments

Comments
 (0)