Array Searching
In the previous screen, we learned about arrays and how to manipulate them. Now, let's explore the topic of array searching.
Array searching involves finding the position or index of a specific element in an array. This operation can be useful in various scenarios, such as locating a value, checking for the presence of an element, or performing further operations on the found element.
One common technique for array searching is linear search.
Linear Search
Linear search is a simple searching algorithm that sequentially checks each element in the array until the target element is found or the end of the array is reached.
Here's an example of implementing linear search in C++:
1#include <iostream>
2using namespace std;
3
4int main() {
5 int arr[] = {2, 4, 6, 8, 10};
6 int target = 6;
7 int n = sizeof(arr) / sizeof(arr[0]);
8
9 for (int i = 0; i < n; i++) {
10 if (arr[i] == target) {
11 cout << "Element found at index " << i << endl;
12 break;
13 }
14 }
15
16 return 0;
17}
In the code snippet above, we have an array arr
containing numbers and a target value target
that we want to search for. We iterate through each element of the array and check if it matches the target value. If a match is found, we print the index at which the element is found.
Linear search has a time complexity of O(n), where n is the number of elements in the array. This means that in the worst-case scenario, it may need to iterate through all elements in the array.
While linear search is a simple and straightforward technique, it may not be efficient for large arrays. In upcoming screens, we will explore more advanced array searching algorithms that offer better performance for different scenarios.
xxxxxxxxxx
using namespace std;
int main() {
// Linear Search
int arr[] = {2, 4, 6, 8, 10};
int target = 6;
int n = sizeof(arr) / sizeof(arr[0]);
for (int i = 0; i < n; i++) {
if (arr[i] == target) {
cout << "Element found at index " << i << endl;
break;
}
}
return 0;
}