Linear Search in C
Linear Search in C
Arsalan
Habib ur Rehman
Linear Search in
C++
Linear search is a type of sequential searching algorithm. In this
method, every element within the input array is traversed and
compared with the key element to be found. If a match is found in
the array the search is said to be successful; if there is no match
found the search is said to be unsuccessful and gives the worst-
case time complexity.
Algorithm
Definition
1 Sequential 2 Index Traversal
Comparison The algorithm starts at
The algorithm compares the first index (0) and
the target value with moves through the array,
each element in the incrementing the index
array, one by one, until a with each comparison.
match is found or the end
of the array is reached.
3 Return Index or -1
If the target value is found, the algorithm returns the index
of the match. If no match is found, it returns -1.
Understanding the
Algorithm
Step 1
1
Initialize the index to 0, indicating the start of the
array.
Step 2
2
Compare the target value with the element at the
current index.
Step 3
3
If a match is found, return the current index. If not,
increment the index and repeat the process.
Code Walkthrough with Array
Visualization
int arr[10]={10,14,19,26,27,31,33,35,42,44};
int n;
cout<<"ENTER THE NUMBER YOU WANT TO SEARCH:”
;
cin>>n;
for(int i=0;i<10;i++)
{ if(arr[i]==n)
{ cout<<"NUMBER FOUND AT INDEX "<<i; }
}
Code Walkthrough with Linked List Visualization
bool searchLinkedList(struct Node* head, int target)
{
while (head != nullptr)
{ if (head->data == target)
{ return true;
} // Value found