You are on page 1of 4

EX NO:

DATE: LINEAR SEARCH

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.

Step 7: Stop the program.

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++;
}

long int key = 999441;

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();

cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;


printf("%f \n", cpu_time_used);

return 0;
}

SOURCE CODE FOR GRAPH:


import numpy as np
import matplotlib.pyplot as plt

arr1 = np.array([50, 200, 500, 1000])

bcarray = np.array([5, 20, 50, 100])


avgcase = np.array([25, 100, 250, 500])
wcarray = np.array([30, 120, 300, 600])

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()

arrelements = np.array([10000, 50000, 100000, 500000, 1000000])


exetime = np.array([0.0005, 0.002, 0.004, 0.02, 0.04])
exetimeavg = np.array([0.0008, 0.003, 0.005, 0.025, 0.05])
exetimeworst = np.array([0.001, 0.005, 0.009, 0.03, 0.06])
plt.figure(figsize=(10, 5))
plt.plot(arrelements, exetime, label="Best Case")
plt.plot(arrelements, exetimeavg, label="Average Case")
plt.plot(arrelements, exetimeworst, label="Worst Case")
plt.legend()
plt.title("EXECUTION TIME")
plt.xlabel("Input Size")
plt.ylabel("Execution Time (in seconds)")
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.

You might also like