Binary search Algorithm in data structure and C++

Binary search: if the items in an array are in some order (ascending or descending) then we can obtain much better performance with an algorithm called binary search. In binary search, we first compare the KEY with the items in the middle position of the array. If it is matches, the search process is terminated with the current location  (middle+1) from where the value is found. If the key is less than middle key, then the sought item must be searched in the lower half of the array, otherwise the sought item must be searched in the upper half of the array so we repeat the search procedure on the lower or upper half of the array with updated starting and terminating indexes.

Algorithm for binary search
Step 1: IF(LENGTH=0) THEN
(i) output"array is empty"
(ii) Exit
Else 
(a) Initialize: start=0, end= LENGTH-1
(b) While ( start<=end) DO
middle=(start+end)/2

Step 2: IF (KEY=ARRAY[Middle]) then
a. Location=middle+1
b. found=1
c. break

Else if(KEY<ARRAY[middle]) then
a. end=middle-1

Step 3: Else
a. start=middle+1
Step 4: END IF
Step 5: END WHILE
Step 6: End IF
step 7: Stop
Description of and Binary search algorithm:
This algorithm will search a given value from the array. the process of search will start from middle of the array. IF match is successful the search process will be terminated saving the index into location. IF the KEY is greater than the middle value of the array the half portion of the array will search and then find the key and its location. This process of search will be continue until the match is found or all sub portions of ARRAY are visited alliteratively.

C/C++  Code for Binary search
void BSEARCH(int ARRAY[], int LENGTH, int KEY, int LOCATION)
{
if ( LENGTH==0)
cout<<"\n Array is Empty";
else
{
int start=0, end=LENGTH-1,Found=0;
while(start<=end)
{
int middle=(start+end)/2;
if (KEY=ARRAY[Middle])
{
LOCATION= Middle+1;
found=1;
break;
}
else if (KEY<ARRAY[middle])
end=middle-1;
else
start=middle+1;
}
}




Comments