🔍 Linear Search in C++ – Explained with Example & Code
📘 What You'll Learn:
-
What is Linear Search?
-
How does it work in C++?
-
Real C++ code with copy feature
-
Output with explanation
-
Benefits of using Linear Search
🧾 Introduction
Linear search, also known as sequential search, is the simplest searching algorithm used in computer science. Whether you’re a beginner in coding or preparing for interviews, understanding linear search in C++ is essential. It is beginner-friendly and often used in basic programming projects or educational environments.
This article will walk you through how linear search works in C++, explain it with examples, and show the actual code you can copy and run on your system.
📘 What is Linear Search?
Linear search is a method to find an element in a list or array by checking each element one by one from the beginning until the desired element is found or the list ends.
It’s not the most efficient for large datasets but is easy to implement and understand.
👨💻 Linear Search in C++ Code
Below is the clean, well-commented C++ code for linear search. You can copy and use it in your compiler or IDE.
#include <iostream>
using namespace std;
int linearSearch(int arr[], int size, int key) {
for(int i = 0; i < size; i++) {
if(arr[i] == key)
return i; // Return index if key is found
}
return -1; // Return -1 if key is not found
}
int main() {
int arr[] = {5, 8, 12, 20, 45};
int key = 20;
int size = sizeof(arr)/sizeof(arr[0]);
int result = linearSearch(arr, size, key);
if(result != -1)
cout << "Element found at index " << result << endl;
else
cout << "Element not found." << endl;
return 0;
}
🖥 Sample Output
Element found at index 3
In this case, the element 20
is found at index 3
in the array.
📘 How It Works
-
The program defines a linear search function.
-
It loops through the array from start to finish.
-
If the target value is found, it returns the index.
-
If not found after the loop, it returns -1.
-
The main function displays whether the element is found or not.
🧠 Conclusion
Linear Search is a great algorithm for beginners learning how to search through data. While not suitable for large datasets, it is an excellent entry point to learn more complex algorithms like binary search or hash-based searching.
With the provided C++ code, you can easily implement and understand how linear search works. Keep experimenting and happy coding!
Post a Comment