LabVIEW

cancel
Showing results for 
Search instead for 
Did you mean: 

Binary search 1D array example code bug

Highlighted
Tried to add this as a comment to the Binary Search 1D Array example code in the NI Developer Zone, but I thought I'd add it here as well. The code example is found at:

http://sine.ni.com/apps/we/niepd_web_display.display_epd4?p_guid=B45EACE3E46E56A4E034080020E74861

(At the time of this writing) Using the code there to perform a numeric binary search for the value of zero causes a return value of 2147483647 when zero is not in the input array and every value of the input array is greater than zero. The return value should be -1.

This is caused by a bit shift of an I32 value of zero, creating a search index of 2147483647. When the input array is indexed there, it returns (unless you have a VERY large array) a default value of zero. This matches the search value of zero, and the algorithm returns 2147483647, believing it has found a match.

I fixed my version of this code by simply returning a -1 if the found index was greater than the size of the input array.

Hope this shows up for those using that code!

Joe Z.
0 Kudos
Message 1 of 2
(1,335 Views)
Highlighted
Hi Joe Z,

The example certainly does not behave as expected when searching for a '0' in an array which contains all positive numbers, and no element with a value of '0'. As you say, the source of the behavior is the shift function which is used to divide by two.

Attached to this post is a screen shot of an alternative fix. I will be taking the example off line shortly to correct this error.

Scott Y
NI
0 Kudos
Message 2 of 2
(1,304 Views)