Lab Record Format
Program/output On The Left Page. |
Aim, Description ,analysis and results on the Right
Page Linear Search |
// Linear Search in C #include <stdio.h> int main() { int arr[100], n, target, i, found = 0; printf("Enter the number of elements: "); scanf("%d", &n); printf("Enter the elements:\n"); for(i = 0; i < n; i++) { scanf("%d", &arr[i]); } printf("Enter the element to search: "); scanf("%d", &target); for(i = 0; i < n; i++) { if(arr[i] == target) { printf("Element found at position %d\n", i); found = 1; break; } } if(!found) { printf("Element not found\n"); } return 0; } ๐งช
Sample Input and Output
๐น Sample Input 1 (Element Present at Beginning):Best Case
Enter the number of elements: Enter the elements: Enter the element to search:
๐น Output:
๐น Sample Input 2 (Element Present in the Middle):
Enter the number of elements: Enter the elements: Enter the element to search:
๐น Output:
๐น Sample Input 3 (Element Present at End):
Enter the number of elements: Enter the elements: Enter the element to search:
๐น Output:
๐น Sample Input 4 (Element Not Present):Worst Case
Enter the number of elements: Enter the elements: Enter the element to search:
๐น Output:
Element
|
Aim:
To implement and understand the working of the Linear Search algorithm to
search for an element in a list/array. Description: Linear Search, also known as sequential
search, is a simple searching algorithm that checks each element of
the list one by one until the desired element (called the key or target) is found or the list ends. The algorithm begins at the first element and
compares each element with the key: ·
If a match is found, the index of the element
is returned. ·
If no match is found by the end of the list,
the algorithm returns that the element is not present. Linear search is
straightforward and does not require the list to be sorted. It is most useful
for small datasets or when the
list is unsorted. Step-by-Step
Algorithm:
Analysis:
๐ Time Complexity:
·
Best
Case: O(1) → when the element is at the first position. ·
Worst
Case: O(n) → when the element is not found or at the last position. ·
Average
Case: O(n/2) ≈ O(n) Space Complexity:
·
O(1) → as it uses a constant amount of extra
space. Limitations:
·
Inefficient for large lists compared to more
advanced algorithms like Binary Search (which requires sorted data). ·
Performance degrades linearly as list size
increases. Advantages:
·
Very simple to implement. ·
Works on both sorted and unsorted lists. Result:
The Linear Search algorithm was successfully
implemented. The working of the algorithm was verified
using multiple test cases with: ·
Target at the beginning ·
Target in the middle ·
Target at the end ·
Target not present in the list The output matched the expected results in all
test cases. |
Comments
Post a Comment