0% found this document useful (0 votes)
7 views

Linear Search C

Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Linear Search C

Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

#include <stdio.

h>

// Function to perform linear search


// Returns the index of the target if found, otherwise returns -1
int linear_search(int arr[], int size, int target) {
// Iterate through each element in the array
for (int i = 0; i < size; i++) {
// If current element matches the target
if (arr[i] == target) {
return i; // Return the index of the found element
}
}

// If target is not found after checking all elements


return -1;
}

// Example usage of linear search


int main() {
// Sample array
int arr[] = {10, 25, 35, 45, 60, 70, 80, 90, 100};
int size = sizeof(arr) / sizeof(arr[0]);

// Elements to search
int target1 = 45;
int target2 = 55;

// Perform linear search


int result1 = linear_search(arr, size, target1);
int result2 = linear_search(arr, size, target2);

// Print results
if (result1 != -1) {
printf("%d found at index %d\n", target1, result1);
} else {
printf("%d not found in the array\n", target1);
}

if (result2 != -1) {
printf("%d found at index %d\n", target2, result2);
} else {
printf("%d not found in the array\n", target2);
}

return 0;
}

/*
Time Complexity:
- Best Case: O(1) - when the target is the first element
- Worst Case: O(n) - when the target is the last element or not present
- Average Case: O(n)

Space Complexity: O(1) - only uses a constant amount of extra space

Pros of Linear Search:


- Simple to implement
- Works on unsorted arrays
- Efficient for small arrays or arrays with few elements
Cons of Linear Search:
- Slow for large arrays
- Always scans entire array in worst case
- Less efficient compared to binary search for sorted arrays
*/

You might also like