Linear Search in C++
Search an unsorted array with linear search in C++, checking each element until the key is found. Returns the index or -1, and works on any order of data.
1#include <iostream>2using namespace std;34int linearSearch(int arr[], int n, int key) {5 for (int i = 0; i < n; i++) {6 if (arr[i] == key) {7 return i; // Return index if found8 }9 }10 return -1; // Return -1 if not found11}1213int main() {14 int arr[] = {64, 34, 25, 12, 22, 11, 90};15 int n = sizeof(arr) / sizeof(arr[0]);16 int key;1718 cout << "Array: ";19 for (int i = 0; i < n; i++) {20 cout << arr[i] << " ";21 }22 cout << endl;2324 cout << "Enter element to search: ";25 cin >> key;2627 int result = linearSearch(arr, n, key);2829 if (result != -1) {30 cout << "Element found at index: " << result << endl;31 } else {32 cout << "Element not found in array" << endl;33 }3435 return 0;36}
Sample Output
Element found at index: 2
25 is at position 2 (0-based).
In this one
- How linear search checks every element in order
- Why returning -1 signals not found
- Why it works on unsorted data
- Its O(n) cost
How it works
- 1
Print the array.
- 2
Read key (25).
- 3
Compare arr[0], arr[1], arr[2]: match at index 2.
- 4
Return 2 and print it.
Edge cases
Duplicates
Search for a value that appears twice.
The loop returns the first match only.
Key missing
Search for 100.
All n elements are checked and -1 is returned.
What's going on
The program searches for an element in an array using Linear Search. For example:
Linear Search checks each element one by one until it finds a match or exhausts all elements.
Header File Used
#include <iostream>
This header provides:
Understanding Linear Search
Algorithm Concept:
Visual Example:
Array: [64, 34, 25, 12, 22, 11, 90]
Search for: 25
Step 1: Check arr[0] = 64 → not 25, continue
Step 2: Check arr[1] = 34 → not 25, continue
Step 3: Check arr[2] = 25 → match! Return index 2
Function: linearSearch()
int linearSearch(int arr[], int n, int key) {
for (int i = 0; i < n; i++) {
if (arr[i] == key) {
return i; // Return index if found
}
}
return -1; // Return -1 if not found
}
How it works:
Step-by-Step Algorithm
For each element in array:
Step 1: Check Current Element
Step 2: Move to Next Element
Step 3: End of Array
Example (searching for 25):
Time and Space Complexity
Time Complexity:
Space Complexity: O(1)
When to Use Linear Search
Best For:
Not Recommended For:
Important Considerations
Works on Any Array:
Return Value:
Comparison Count:
return 0;
This ends the program successfully.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Worst-case comparisons for n = 100?
Pick an answer to check it.
Question 2
Does linear search need sorted data?
Pick an answer to check it.
Questions people ask
When to use it?
Small or unsorted arrays, or when searching once.
Library version?
std::find(arr, arr + n, key) returns a pointer to the match or arr + n.
Why -1?
It can never be a valid index.