Searching is a process of finding an element in a list or an array. It is a common operation in computer programming, and there are several algorithms and techniques that can be used to search for an element in an array in C language.
One of the simplest and most intuitive search techniques is linear search, where the elements of the array are compared sequentially with the search key until a match is found or the end of the array is reached. Here is an example of linear search in C:
#include <stdio.h>
// function to search for an element in an array using linear search
int linear_search(int array[], int size, int key) {
// iterate through the array
for (int i = 0; i < size; i++) {
if (array[i] == key) { // if the element is found, return its index
return i;
}
}
return -1; // if the element is not found, return -1
}
// main function
int main() {
int array[] = {1, 2, 3, 4, 5}; // declare and initialize an array
int size = sizeof(array) / sizeof(array[0]); // calculate the size of the array
int key = 3; // search key
// search for the key in the array using linear search
int index = linear_search(array, size, key);
if (index == -1) { // if the element is not found
printf("Element not found\n");
} else { // if the element is found
printf("Element found at index %d\n", index);
}
return 0;
}
In this example, the function “linear_search” takes an array, its size, and the search key as arguments, and returns the index of the element if it is found, or -1 if it is not found. The main function declares and initializes an array, and calls the “linear_search” function to search for an element in the array. The output of the program will be “Element found at index 2”, since the element 3 is found at index 2 in the array.
Another efficient search technique for sorted arrays is binary search, which works by dividing the array into two halves and comparing the search key with the middle element. Here is an example of binary search in C:
#include <stdio.h>
// function to search for an element in a sorted array using binary search
int binary_search(int array[], int size, int key) {
int left = 0; // left index
int right = size - 1; // right index
while (left <= right) { // while the left index is less than or equal to the right index
int middle = (left + right) / 2; // calculate the middle index
if (array[middle] == key) { // if the middle element is the search key, return its index
return middle;
} else if (array[middle] < key) { // if the middle element is less than the search key
left = middle + 1; // move the left index to the right of the middle element
} else { // if the middle element is greater than the search key
right = middle - 1; // move the right index to the left of the middle element
}
}
return -1;