**Binary search is a vast improvement over the sequential search. For binary search to work, the item in the list must be in assorted order. The approach employed in the binary search is divid and conquer. If the list to be sorted for a specific item is not sorted, binary search fails.**

__Description:__**ALGORITHM:**

BINARY SEARCH

1. Start

2. Read the value of n

3. for i=1 to n increment in steps of 1

Read the value of ith element into array

4. Read the element(x) to be searched

5. search<--binary(a,n,x)

6. if search equal to 0 goto step 7 otherwise goto step 8

7. print unsuccessful search

8. print successful search

9. stop

BINARY SEARCH FUNCTION

1. start

2. initialise low to 1 ,high to n, test to 0

3. if low<= high repeat through steps 4 to 9 otherwise goto step 10

4. assign (low+high)/2 to mid

5. if m<k[mid] goto step 6 otherwise goto step 7

6. assign mid-1 to high goto step 3

7. if m>k[mid] goto step 8 otherwise goto step 9

8. assign mid+1 to low

9. return mid

10. return 0

11.stop

**Program:**

#include<stdio.h>

main()

{

int i,n,key,a[10],low,high,mid;

clrscr();

printf("enter range for array:");

scanf("%d",&n);

printf("enter elements into array:");

for(i=0;i<n;i++)

scanf("%d",&a[i]);

printf("the search element:");

scanf("%d",&key);

low=0;

high=n-1;

for(i=0;i<n;i++)

{

mid=(low+high)/2;

if(a[mid]==key)

{

printf("element %d found at %d",key,mid);

break;

}

if(key<a[mid])

high=mid;

else

low=mid+1;

if(i==n-1)

printf("element %d not found in array",key);

}

getch();

}

**Input/Output:**

enter range for array:4

enter elements into array:12 23 34 45

the search element:45

element 45 found at 3

enter range for array:5

enter elements into array:1 34 56 78 88

the search element:45

element 45 not found in array

__the program is error free__

**conclusion:**

**VIVA QUESATIONS****1)**Define Binary search ?

**Ans:**Binary search is a vast improvement over the sequential search. For binary search to work, the item in the list must be in assorted order. The approach employed in the binary search is divid and conquer. If the list to be sorted for a specific item is not sorted, binary search fails.

## No comments:

## Post a Comment