1. Introduction
Linear Search is one of the simplest searching algorithms. It sequentially checks each element of the list or array until a match is found or the whole list has been searched.
2. Program Overview
In this program, we will:
1. Implement the linearSearch function to search for an element in an array.
2. Search for a specified element in an array.
3. Display whether the element is found and its position if it exists.
3. Code Program
#include <stdio.h>
// Function for linear search
int linearSearch(int arr[], int size, int x) {
for (int i = 0; i < size; i++) {
if (arr[i] == x) {
return i; // Element found, return index
}
}
return -1; // Element not found, return -1
}
// Driver code
int main() {
int arr[] = {2, 4, 0, 1, 9, 6, 8, 7, 5, 3};
int n = sizeof(arr) / sizeof(arr[0]);
int x = 5; // Element to be searched
printf("Array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
int result = linearSearch(arr, n, x);
if (result != -1) {
printf("Element %d is present at index %d.\n", x, result);
} else {
printf("Element %d is not present in the array.\n", x);
}
return 0;
}
Output:
Array: 2 4 0 1 9 6 8 7 5 3 Element 5 is present at index 8.
4. Step By Step Explanation
1. The linearSearch function accepts an array, its size, and the element to be searched for. It then iterates through the array. If the element is found, it returns the index. If not, it returns -1.
2. In the main function, we initialize an array and the element we want to search for.
3. We then call the linearSearch function and store the result in the result variable.
4. Based on the result, we print whether the element was found and its position or specify that the element is not present in the array.
Linear Search has a time complexity of O(n) in the worst case, which happens when the element to be searched for is the last element or is not in the array at all. Though it's not the most efficient search algorithm, it's straightforward and works well for small datasets.
Comments
Post a Comment
Leave Comment