Table of contents | |
Introduction | |
How does Linear Search work? | |
Pseudocode for Linear Search | |
Implementing Linear Search in C++ | |
Sample Problems |
In the world of data structures and algorithms, the linear search algorithm is one of the simplest and most fundamental searching techniques. It is used to find a specific element in a given list or array by sequentially checking each element until a match is found. In this article, we will explore the concept of linear search, its implementation in C++, and provide examples and sample problems to help you understand it better.
The linear search algorithm works by iterating through each element of the array and comparing it with the target element we are searching for. If a match is found, the index of the element is returned. If the entire array is traversed and no match is found, a special value (e.g., -1) can be returned to indicate the element is not present.
Here is the pseudocode for the linear search algorithm:
Now, let's see how we can implement the linear search algorithm in C++.
#include<iostream>
using namespace std;
int linearSearch(int arr[], int size, int target) {
for(int i = 0; i < size; i++) {
if(arr[i] == target)
return i;
}
return -1;
}
int main() {
int arr[] = {5, 10, 15, 20, 25};
int size = sizeof(arr) / sizeof(arr[0]);
int target = 15;
int index = linearSearch(arr, size, target);
if(index == -1)
cout << "Element not found in the array";
else
cout << "Element found at index " << index;
return 0;
}
Explanation of the code:
Here are some sample problems you can solve using the linear search algorithm:
Problem 1: Given an array of integers, find the first occurrence of a specific element and return its index. If the element is not present, return -1.
int firstOccurrence(int arr[], int size, int target) {
for(int i = 0; i < size; i++) {
if(arr[i] == target)
return i;
}
return -1;
}
Problem 2: Given an array of strings, find the count of a specific string in the array.
int countOccurrences(string arr[], int size, string target) {
int count = 0;
for(int i = 0; i < size; i++) {
if(arr[i] == target)
count++;
}
return count;
}
The linear search algorithm is a simple yet powerful technique to find an element in an array or list. It is particularly useful when the array is not sorted or when the array size is small. In this article, we discussed the concept of linear search, provided an implementation in C++, explained the code, and presented sample problems to enhance your understanding. Practice implementing and solving linear search problems to strengthen your grasp of this fundamental searching algorithm.
153 videos|115 docs|24 tests
|
|
Explore Courses for Software Development exam
|