0% found this document useful (0 votes)
22 views8 pages

Linear Search in C

Uploaded by

Habib rehman
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views8 pages

Linear Search in C

Uploaded by

Habib rehman
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 8

Muhammad

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

head = head->next; } // Move to


the next node
return false;
} // Value not found
Time Complexity and
Efficiency The target value is found at the
Best Case first index, so the algorithm only
needs to perform one
comparison. Time complexity is
O(1).
Worst Case The target value is not found, so
the algorithm must compare the
target with each element in the
array. Time complexity is O(n).

Average Case On average, the algorithm will


need to compare the target with
half the elements in the array.
Time complexity is O(n/2) =
O(n).
Thank
You!

You might also like