I just wanted to know If using function in the programs speeds up execution time?
Say, I have simple binary search Program
#include <stdio.h>
int main()
{
int c, first, last, middle, n, search, array[100];
scanf("%d",&n);
for ( c = 0 ; c < n ; c++ )
scanf("%d",&array[c]);
scanf("%d",&search);
first = 0;
last = n - 1;
middle = (first+last)/2;
while( first <= last )
{
if ( array[middle] < search )
first = middle + 1;
else if ( array[middle] == search )
{
printf("%d found at location %d.\n", search, middle+1);
break;
}
else
last = middle - 1;
middle = (first + last)/2;
}
if ( first > last )
printf("Not found! %d is not present in the list.\n", search);
return 0;
}
And Same Program using function.
I have just added the function
int binarysearch(int *array,int m,int n)
{
int l,u,mid;
l=0,u=n-1;
while(l<=u)
{
mid=(l+u)/2;
if(m==a[mid])
{
c=1;
break;
}
else if(m<a[mid])
{
u=mid-1;
}
else
l=mid+1;
}
return mid;
}
Code is just for understanding purpose!
Now Which will run faster? Program using Function or Iterative Programs? I'm talking in general not about any specific program.