Monday, 20 December 2010

Algorithm for To perform the binary search operation

Description:

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.


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 i th element into array
4. Read the element(x) to be searched 
5. search<--binary(a,n,x) 
6. if search equal to 0 go to step 7 otherwise go to 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

  Output:

enter range for array:4
enter elements into array:12 23 34 45 
the search element:45
element 45 found at 4


enter range for array:5
enter elements into array:1 34 56 78 88 the search element:45
element 45 not found in array

Conclusion: the program is error free

More Explanation:

The search always needs to track three values – the midpoint, the first position in the scope and the last position in the scope. With each pass, the algorithm narrows the search scope by half. With each subsequent pass of the data, the algorithm re-calculates the midpoint and searches for the target. First, it searches for the target at the midpoint of the list. It can then determine if the target is in the first half of the list or the second, thus eliminating half of the values. The binary search divides the list into two halves. We should use the binary search on large lists (>50 elements) that are sorted.




VIVA QUESTIONS

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 divide and conquer. If the list to be sorted for a specific item is not sorted, binary search fails.

You may like the following posts:Binary Search
Example program on Binary Search
Algorithm on Binary Search
Flow chart on Binary Search
Programs on data structures
Data structures using Java

No comments:

Post a Comment