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