Time complexities of any algorithm can be expressed by using best,Worst and Average case.
The Time Complexity of Linear Search is shown By using Program.
//Linear search program
#include<stdio.h>
int main()
{
int arr[]={1,10,30,40,50,60,77,56,57};
int x=57;
int n=sizeof(arr);
printf("Element %d is found at %d",x,search(arr,n,x));
return(0);
}
int search(int arr[],int n,int x)
{
int i;
for(i=0;i<n;i++)
{
if(arr[i]==x)
return(i);
}
return(-1);
}
Explanation:
// Worst case of this algorithm will be Θ(n) if element will be found at last position.
//For Average case,we have to search for all the inputs(taking sum of all inputs) and then divide it by no.of inputs.
i.e.
// Best case will occur when element will be found at first position.Best Case means how fast the algorithm can run
The Time Complexity of Linear Search is shown By using Program.
//Linear search program
#include<stdio.h>
int main()
{
int arr[]={1,10,30,40,50,60,77,56,57};
int x=57;
int n=sizeof(arr);
printf("Element %d is found at %d",x,search(arr,n,x));
return(0);
}
int search(int arr[],int n,int x)
{
int i;
for(i=0;i<n;i++)
{
if(arr[i]==x)
return(i);
}
return(-1);
}
Explanation:
// Worst case of this algorithm will be Θ(n) if element will be found at last position.
//For Average case,we have to search for all the inputs(taking sum of all inputs) and then divide it by no.of inputs.
i.e.
// Best case will occur when element will be found at first position.Best Case means how fast the algorithm can run
No comments:
Post a Comment