= { , , , , , , , } target = Output: - (not found) Example : . . . Binary Search Binary search also called half-interval search algorithm.
It finds the position of a search element within a sorted array. The binary search algorithm can be done as divide-and-conquer search algorithm and executes in logarithmic time. Procedure for Binary search . Start with the middle element: • If the search element is equal to the middle element of the array i.e., the middle value = number of elements in array/ , then return the index of the middle element.
• If not, then compare the middle element with the search value, • If the search element is greater than the number in the middle index, then select the elements to the right side of the middle index, and go to Step- . • If the search element is less than the number in the middle index, then select the elements to the left side of the middle index, and start with Step- . . When a match is found, display success message with the index of the element matched.
. If no match is found for all comparisons, then display unsuccessful message. Binary Search Working principles List of elements in an array must be sorted first for Binary search. The following example describes the step by step operation of binary search.
Consider the following array of elemnts, the array is being sorted so it enables to do the binary search algorithm. Let us assume that the search element is and we need to search the location or index of search element using binary search. First, we find index of middle element of the array by using this formula : mid = low + (high - low) / Here it is, + ( - ) / = (fractional part ignored). So, is the mid value of the array.