Loading…
DAA · Searching · Program 01 · In the record
Write a program in c to search an element using linear search and find its execution time using the time function.
Algorithm: LinearSearch(A, n, x) 1. Start 2. For i <- 0 to (n-1) do 3. if x == A[i] then 4. print "Element Found" 5. exit 6. If (i==n) then 7. print "Element Not Found" 8. Stop
1#include<stdio.h>2#include<time.h>3 4int main() {5 int n,i,x,count=0;6 printf("Enter the number of elements:");7 scanf("%d",&n);8 int a[n];9 printf("Enter the elements:");10 for(i=0;i<n;i++)11 scanf("%d",&a[i]);12 printf("Enter the element to search:");13 scanf("%d",&x);14 15 clock_t start=clock();16 for(i=0;i<n;i++) {17 count++;18 if(x==a[i])19 break;20 }21 clock_t end=clock();22 double time_taken=(double)(end-start)/CLOCKS_PER_SEC;23 24 if(i==n)25 printf("\n%d is not found",x);26 else27 printf("\n%d is found at position %d",x,i+1);28 printf("\nNumber of comparisons:%d",count);29 printf("\nTime taken:%f seconds",time_taken);30 printf("\nTime complexity: best case O(1), worst case O(n)");31 printf("\nSpace complexity: O(1)");32 printf("\n");33 return 0;34}6 ⏎ 14 27 8 35 19 42 ⏎ 35Enter the number of elements:6 Enter the elements:14 27 8 35 19 42 Enter the element to search:35 35 is found at position 4 Number of comparisons:4 Time taken:0.000003 seconds Time complexity: best case O(1), worst case O(n) Space complexity: O(1)
Run program 01 in your browser
C · clang → WebAssembly. Change the code or the input, run it, break it, and see what happens.