# Binary search program in cpp using divide and conquer method

The following code offers an interface compatible with the requirement of this task, and returns either the index of the element if it has been found or f otherwise. This version is designed for maintaining a sorted array. If the item is not found, then then location returned is the proper insertion point for the item.

This could be used in an optimized Insertion sort , for example. This has the array indexed from 1 to N, and the "not found" return code is zero or negative. Changing the search to be for A first: For the more advanced fortrans, declaring the parameters to be INTENT IN may help, as despite passing arrays "by reference" being the norm, the newer compilers may generate copy-in, copy-out code, vitiating the whole point of using a fast binary search instead of a slow linear search.

In such a situation however, preparing in-line code may be the better move: Later compilers offer features allowing the development of "generic" functions so that the same function name may be used yet the actual routine invoked will be selected according to how the parameters are integers or floating-point, and of different precisions. There would still need to be a version of the function for each type combination, each with its own name.

Unfortunately, there is no three-way comparison test for character data. The use of "exclusive" bounds simplifies the adjustment of the bounds: The "inclusive" bounds version by contrast requires two manipulations of L and R at every step - once to see if the span is empty, and a second time to locate the index to test. Imagine a test array containing the even numbers: A count could be kept of the number of probes required to find each of those four values, and likewise with a search for the odd numbers 1,3,5,7,9 that would probe all the places where a value might be not found.

Plot the average number of probes for the two cases, plus the maximum number of probes for any case, and then repeat for another number of elements to search. With only one element in the array to be searched, all values are the same: The point of this is that the IF-test is going to initiate some jumps, so why not arrange that one of the bound adjustments needs no subsequent jump to the start of the next iteration - in the first version, both bound adjustments needed such a jump, the GO TO 1 statements.

This was done by shifting the code for label 2 up to precede the code for label 1 - and removing its now pointless GO TO 1 executed each time , but adding an initial GO TO 1, executed once only. This sort of change is routine when manipulating spaghetti code It is because the method involves such a small amount of effort per iteration that minor changes offer a significant benefit.

A lot depends on the implementation of the three-way test: These branch tests may in turn be made in an order that notes which option if any involves "falling through" to the next statement, thus it may be better to swap the order of labels 3 and 4.

Further, the compiler may itself choose to re-order the various code pieces. An assembler version of this routine attended to all these details. Some compilers do not produce machine code directly, but instead translate the source code into another language which is then compiled, and a common choice for that is C. This is all very well, but C is one of the many languages that do not have a three-way test option and so cannot represent Fortran's three-way IF statement directly.

Before emitting asservations of faith that pseudocode such as. That is, does the compiler make any remark, and does the resulting machine code contain a redundant test? However, despite all the above, the three-way IF statement has been declared deprecated in later versions of Fortran, with no alternative to repeated testing offered.

Incidentally, the exclusive-bounds version leads to a good version of the interpolation search whereby the probe position is interpolated, not just in the middle of the span , unlike the version based on inclusive-bounds. Further, the unsourced offering in Wikipedia contains a bug - try searching an array of two equal elements for that value. There are also functions sort. SearchStrings , and a very general sort. Search function that allows you to binary search a range of numbers based on any condition not necessarily just search for an index of an element in an array.

The algorithm itself, parametrized by an "interrogation" predicate p in the spirit of the explanation above:. The algorithm uses tail recursion, so the iterative and the recursive approach are identical in Haskell the compiler will convert recursive calls into jumps.

J already includes a binary search primitive I. The following code offers an interface compatible with the requirement of this task, and returns either the index of the element if it has been found or 'Not Found' otherwise:.

The remaining search interval is [left, right]. The parts left and right of that interval have been searched. We now want to determine the index at which the element should be inserted to maintain the ordering. As the remaining searching interval is empty now, there is an interval i [0, n-1] with two disjunct intervals i1 [0, left] and i2 [right, n-1] with the following attributes: We now have two possible cases:.

So in case a an insertion must happen on index mid. From the first part follows that mid is in interval [0, left]. From the second part follows that mid is at the right edge of the interval. Binary search From CodeCodex. Retrieved from " http: But we need not stop at arrays — we can generalize the implementation even further to any container permitting random access, such as std:: This is very similar to the above implementation, but with the indexes low and high and the return value replaced by iterators.

Also, by convention, we make "end" point one past the last element to be searched instead of using an inclusive range, resulting in each instance of "end" being adjusted by 1; if the element is not found we can return the initial value of end, since this is outside the range being searched and so not a normal return value.

We can't use std:: This simple test code tries out the final binary search on an array and a vector, using std:: The method takes two arguments: The value to search and the list of values to search in. The input list must be sorted in ascending order prior to searching, else the result of this method is undefined. It must also contain at least one element. Through Java generics, the method can be used with any elements that extend Comparable, like Java number objects or strings, making Java 5 a requirement.