DSA Linear Searching
DSA Linear Searching
Step-by-Step Algorithm
1. Step 1:
3. Step 3:
• If a match is found, return the index of the element.
4. Step 4:
1
C Code for Linear Search
1 // C program to implement Linear Search
2 # include < stdio .h >
3
13 int main () {
14 int arr [] = {10 , 20 , 30 , 40 , 50};
15 int n = sizeof ( arr ) / sizeof ( arr [0]) ;
16 int target = 30;
17
20 if ( result != -1) {
21 printf ( " Element found at index : % d \ n " , result ) ;
22 } else {
23 printf ( " Element not found in the array .\ n " ) ;
24 }
25
26 return 0;
27 }
Explanation of Code
1. The linearSearch function takes the array, its size, and the target ele-
ment as inputs.
2
Real-World Example: Looking for a Book in a
Stack
Imagine you are looking for a specific book in a stack:
This is similar to how Linear Search works by checking each element until a
match is found.
3
Diagrammatic Representation of Linear Search
• Array: [10, 20, 30, 40, 50]
• Target: 30
• Step-by-step:
– Compare with 10 → Not a match
– Compare with 20 → Not a match
– Compare with 30 → Match found
– Return index 2