6. Write a C program for linear search and binary search.
A – Linear Search
#include <stdio.h>
// linear search function that searches the key in arr
int linearSearch(int* arr, int size, int key)
{
// starting traversal
for (int i = 0; i < size; i++) {
// checking condition
if (arr[i] == key) {
return i;
}
}
return -1;
}
int main()
{
int arr[10] = { 3, 4, 1, 7, 5, 8, 11, 42, 3, 13 };
int size = sizeof(arr) / sizeof(arr[0]);
int key = 4;
// calling linearSearch
int index = linearSearch(arr, size, key);
// printing result based on value returned by
// linearSearch()
if (index == -1) {
printf("The element is not present in the arr.");
}
else {
printf("The element is present at arr[%d].", index);
}
return 0;
}
Output
The element is present at arr[1].
B – Binary Search
#include <stdio.h>
int binarySearch(int arr[], int l, int r, int x)
{
// checking if there are elements in the subarray
if (r >= l) {
// calculating mid point
int mid = l + (r - l) / 2;
// If the element is present at the middle itself
if (arr[mid] == x)
return mid;
// If element is smaller than mid, then it can only
// be present in left subarray
if (arr[mid] > x) {
return binarySearch(arr, l, mid - 1, x);
}
// Else the element can only be present in right
// subarray
return binarySearch(arr, mid + 1, r, x);
}
// We reach here when element is not present in array
return -1;
}
int main(void)
{
// taking a sorted array
int arr[] = { 2, 3, 4, 10, 40 };
int size = sizeof(arr) / sizeof(arr[0]);
// element to be searched
int x = 10;
// calling binary search
int index = binarySearch(arr, 0, size - 1, x);
if (index == -1) {
printf("Element is not present in array");
}
else {
printf("Element is present at index %d", index);
}
return 0;
}
Output
Element is present at index 3