Welcome to our tutorial on C Linear Search! In this lesson, we'll learn how to search for an item in an array using the Linear Search algorithm. This technique is fundamental in programming and has real-world applications, such as finding a specific name in a list of contacts or locating a product in an inventory.
Before we dive in, let's make sure you're familiar with some basic concepts:
Linear Search is a simple and naive method used to find an element in an array. It iterates through the array element by element until it finds the desired item or reaches the end of the array.
Here's a step-by-step breakdown of the Linear Search algorithm:
Now, let's write a Linear Search function in C.
#include <stdio.h>
int linear_search(int arr[], int size, int target) {
int i;
for (i = 0; i < size; i++) {
if (arr[i] == target) {
return i;
}
}
return -1;
}š” Pro Tip: It's a good practice to check if the array is not empty before performing a Linear Search.
Let's put our Linear Search function to work! Consider an array containing exam scores:
int scores[] = {85, 67, 91, 78, 92};
int result = linear_search(scores, 5, 92);
if (result != -1) {
printf("The score 92 is at index %d.", result);
} else {
printf("The score 92 is not found in the list.");
}Upon running this code, we'll see that the score 92 is found at index 4.
It's essential to understand that Linear Search has a time complexity of O(n), where n is the number of elements in the array. This means that the algorithm becomes slower as the size of the array increases. Thus, for large datasets, more efficient search algorithms like Binary Search should be used.
What is the time complexity of the Linear Search algorithm?
That's all for today! In the next lesson, we'll learn about Binary Search, an optimization of Linear Search for sorted arrays. Until then, happy coding! š