samedi 18 avril 2015

Time limit exceeded in binary search

I have been working on a program to search an element using binary search but every time i run this program i get a time limit exceeded error. Though i searched about this error but I am unable to find what is the error in this program pls help Here is the code



#include<stdio.h>
int BinarySearch(int low,int high,int *a,int item);
int main(){
int a[50] , i , low , high , n , item , position;

printf("Enter the number of Elements");
scanf("%i",&n);
for(i=0;i<n;i++){
scanf("%i",&a[i]);
}

printf("Enter the Element to be searched");
scanf("%i",&item);
low=0;
high=n-1;
position=BinarySearch(low,high,a,item);

if(position==-1)
printf("Item not found");
else
printf("item was found on the %i position",position);

return 0;
}
int BinarySearch(int low,int high,int *a,int item){
int mid,loc,flag=0;
while (item!= a[mid] && low <= high);
{
mid = (low + high) / 2;

if(a[mid]==item){
loc=mid;
flag=flag+1;
}
else if (item < a[mid])
high = mid - 1;
else
low = mid + 1;
}
if (flag>=1)
return loc;
else
return -1;
}

Aucun commentaire:

Enregistrer un commentaire