arraysgodotgodot4bsearch

Incorrect operation of the bsearch method in godot 4


When I use the .bsearch(0) method in the array a returns 3 to me, although it should be 1 (the method for some reason skips the first 2 values) Why?

a = [-1, 0, -1, 0]
print(a.bsearch(0))

I checked and realized that the method misses the first 2 values in the array, but Why? And how to fixed it?


Solution

  • There are two reasons for the behaviour that you are seeing.

    Firstly, bsearch is meant to be called on a sorted array. Your array is not sorted so it will give unpredictable results.

    Secondly, bsearch takes a second boolean argument: before i.e. a.bsearch(0, true). By default this is false. If it is false, it will give you the index of the last instance of the item. If it is set to true, it will give you the index of the first instance.

    You can look at the documentation for more information: https://docs.godotengine.org/en/stable/classes/class_array.html#class-array-method-bsearch