Professional Documents
Culture Documents
AIM:
To write a program to perform linear search and to analyse its time complexity.
ALGORITHM:
Step 1: Start with an array arr and a target value target.
Step 2: Initialize a variable index to store the index of the target value.
Step 3: Iterate over each element num and its index idx in the array
Step 4: If num equals the target, set index to idx and break the loop.
Step 5: If index != -1, return index as the index of the target value.
Step 6: If the target value is not found, return -1 to indicate that the target is not in the array.
Step 7: At each step of the algorithm, iterate over each element of the array until the target
value is found
Step 8: The time complexity of linear search is O(n), where n is the size of the input array.
SOURCE CODE:
#include<stdio.h>
#include<time.h>
int main() {
clock_t start, end;
double cpu_time_used;
long int arr[1000000];
long int c = 0;
long int i;
for(i = 1; i <= 1000000; i++) {
arr[c] = i;
c++;
}
start = clock();
int found = 0;
for(i = 0; i < 1000000; i++) {
if(arr[i] == key) {
printf("Found at %ld\n", i);
found = 1;
break;
}
}
if (found != 1) {
puts("Not Found");
}
end = clock();
return 0;
}
plt.figure(figsize=(10, 5))
plt.plot(arr1, bcarray, label="BEST")
plt.plot(arr1, wcarray, label="WORST")
plt.plot(arr1, avgcase, label="AVERAGE")
plt.legend()
plt.title("RUNTIME")
plt.xlabel("Input Size")
plt.ylabel("Execution Time (in milliseconds)")
plt.show()
TIME COMPLEXITY:
Best Case: O(1)
Worst Case: O(n)
Average Case: O(n)
OUTPUT:
RESULT:
Thus the program to perform Linear search was implemented and its time complexity
was analysed.