- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Linear Search
Linear searching techniques are the simplest technique. In this technique, the items are searched one by one. This procedure is also applicable for unsorted data set. Linear search is also known as sequential search. It is named as linear because its time complexity is of the order of n O(n).
The complexity of Linear Search Technique
- Time Complexity: O(n)
- Space Complexity: O(1)
Input and Output
Input: A list of data: 20 4 89 75 10 23 45 69 the search key 10 Output: Item found at location: 4
Algorithm
linearSearch(array, size, key)
Input − An sorted array, size of the array and the search key
Output − location of the key (if found), otherwise wrong location.
Begin for i := 0 to size -1 do if array[i] = key then return i done return invalid location End
Example
#include<iostream> using namespace std; int linSearch(int array[], int size, int key) { for(int i = 0; i<size; i++) { if(array[i] == key) //search key in each places of the array return i; //location where key is found for the first time } return -1; //when the key is not in the list } int main() { int n, searchKey, loc; cout << "Enter number of items: "; cin >> n; int arr[n]; //create an array of size n cout << "Enter items: " << endl; for(int i = 0; i< n; i++) { cin >> arr[i]; } cout << "Enter search key to search in the list: "; cin >> searchKey; if((loc = linSearch(arr, n, searchKey)) >= 0) cout << "Item found at location: " << loc << endl; else cout << "Item is not found in the list." << endl; }
Output
Enter number of items: 8 Enter items: 20 4 89 75 10 23 45 69 Enter search key to search in the list: 10 Item found at location: 4
Advertisements