Write C program/algorithm to perform linear search. Find the time complexity for
best, worst and average case for a linear search in an array of n elements. (third semester B Tech CSE)
Answers
Answer:
#include <stdio.h>
void main()
{
int num;
int i, keynum, found = 0;
printf("Enter the number of elements ");
scanf("%d", &num);
int array[num];
printf("Enter the elements one by one \n");
for (i = 0; i < num; i++)
{
scanf("%d", &array[i]);
}
printf("Enter the element to be searched ");
scanf("%d", &keynum);
/* Linear search begins */
for (i = 0; i < num ; i++)
{
if (keynum == array[i] )
{
found = 1;
break;
}
}
if (found == 1)
printf("Element is present in the array at position %d",i+1);
else
printf("Element is not present in the array\n");
}
If the searched element is the first element of the array.
For example:
If the input array is {66, -3, 31}
and the key searched for is 66,
then the expected output will be Position 1.
Best Case Time Complexity : O(1)
If the searched element is other than the first and the last element of the array.
For example:
If the input array is {4, 6, 1, 2, 5, 3}
and if the element searched is 6,
then the expected output will be Position 2.
Average Case Time Complexity : O(n)
If the element searched for is the last element of the array.
For example:
If the input array is {1, 3, 6, 1, 9}
and the key searched for is 9,
then the expected output will be Position 5.
Worst Case Time Complexity : O(n)
Explanation:
Explanation:
Coding hi krte reh jaaoge tum xd xd
Tu dharti pe chahe jaha bhi rahegi, tujhe tere khushbu se pehchaan lunga xd xd xd