1.

Suppose an array P containing float is arranged in ascending order. Write a user defined function in C++ to search for one float from P with the help of binary search method. The function should return an integer 0 to show absence of the number and integer 1 to show the presence of the number in the array. The function should have three parameters: (1) an array P (2) the number DATA to be searched and (3) the number of elements N.

Answer»

int bsearch(float P[10],int DATA,int N)

{ int beg=0,last=N-1,mid;

while(beg<=last)

{ mid=(beg+last)/2;

if(P[mid]==DATA) return 1; //element is present in array 

else if(DATA>P[mid]) beg=mid+1;

else last=mid-1;

}

return 0;  //element is absent in array

}



Discussion

No Comment Found

Related InterviewSolutions