Skip to content

Commit 5ac3f31

Browse files
Merge pull request #108 from Meharsh7804/main
Added Succesfully
2 parents 1b4f2d8 + 9cb6acb commit 5ac3f31

File tree

2 files changed

+77
-0
lines changed

2 files changed

+77
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
#include <iostream>
2+
using namespace std;
3+
4+
// Function to perform Binary Search
5+
int binarySearch(int arr[], int size, int target) {
6+
int left = 0, right = size - 1;
7+
8+
while (left <= right) {
9+
int mid = left + (right - left) / 2; // Calculate mid index
10+
11+
// Check if the target is at mid
12+
if (arr[mid] == target) {
13+
return mid; // Return the index if found
14+
}
15+
16+
// If target is greater, ignore the left half
17+
if (arr[mid] < target) {
18+
left = mid + 1;
19+
}
20+
// If target is smaller, ignore the right half
21+
else {
22+
right = mid - 1;
23+
}
24+
}
25+
26+
return -1; // Return -1 if the target is not found
27+
}
28+
29+
int main() {
30+
int arr[] = {9, 11, 21, 34, 45, 56, 78};
31+
int size = sizeof(arr) / sizeof(arr[0]);
32+
int target = 56;
33+
34+
// Call the binary search function
35+
int result = binarySearch(arr, size, target);
36+
37+
// Output the result
38+
if (result != -1) {
39+
cout << "Element found at index: " << result << endl;
40+
} else {
41+
cout << "Element not found!" << endl;
42+
}
43+
44+
return 0;
45+
}
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
#include <iostream>
2+
using namespace std;
3+
4+
// Function to perform Linear Search
5+
int linearSearch(int arr[], int size, int target) {
6+
// Iterate through the entire array
7+
for (int i = 0; i < size; i++) {
8+
// Check if the current element matches the target
9+
if (arr[i] == target) {
10+
return i; // Return the index of the target element
11+
}
12+
}
13+
return -1; // Return -1 if the target is not found
14+
}
15+
16+
int main() {
17+
int arr[] = {34, 78, 21, 56, 11, 9, 45};
18+
int size = sizeof(arr) / sizeof(arr[0]);
19+
int target = 56;
20+
21+
// Call the linear search function
22+
int result = linearSearch(arr, size, target);
23+
24+
// Output the result
25+
if (result != -1) {
26+
cout << "Element found at index: " << result << endl;
27+
} else {
28+
cout << "Element not found!" << endl;
29+
}
30+
31+
return 0;
32+
}

0 commit comments

Comments
 (0)