Calculating midpoint index in binary search

前端 未结 3 765
無奈伤痛
無奈伤痛 2021-02-05 22:26

So, the correct way of calculating mid in a binary search is mid = low + ((high - low) / 2) in order to handle overflow errors.

My implementati

3条回答
  •  心在旅途
    2021-02-05 23:10

    If there is no possibility of overflow, the overflow-safe way of computing the midpoint is technically unnecessary: you can use the unsafe formula if you wish. However, it's probably a good idea to keep it there anyway, in case that your program gets modified some day to break your assumptions. I think that adding a single CPU instruction to make your code future-proof is a great investment in maintainability of your code.

提交回复
热议问题