Linear Search
Linear Search Algorithm in C++ (Complete Implementation)
BeginnerTopic: Sorting & Searching Programs
C++ Linear Search Program
This program helps you to learn the fundamental structure and syntax of C++ programming.
#include <iostream>
using namespace std;
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
}
int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr) / sizeof(arr[0]);
int key;
cout << "Array: ";
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
cout << "Enter element to search: ";
cin >> key;
int result = linearSearch(arr, n, key);
if (result != -1) {
cout << "Element found at index: " << result << endl;
} else {
cout << "Element not found in array" << endl;
}
return 0;
}Output
Array: 64 34 25 12 22 11 90 Enter element to search: 25 Element found at index: 2
Understanding Linear Search
Linear Search sequentially checks each element of the array until a match is found or the entire array has been searched. Time Complexity: O(n) worst case, O(1) best case. Space Complexity: O(1). It works on both sorted and unsorted arrays but is inefficient for large datasets.
Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.