How to perform a binary search on IList?

前端 未结 11 1393
执念已碎
执念已碎 2020-11-28 09:32

Simple question - given an IList how do you perform a binary search without writing the method yourself and without copying the data to a type with bui

11条回答
  •  半阙折子戏
    2020-11-28 10:19

    I like the solution with the extension method. However, a bit of warning is in order.

    This is effectively Jon Bentley's implementation from his book Programming Pearls and it suffers modestly from a bug with numeric overflow that went undiscovered for 20 years or so. The (upper+lower) can overflow Int32 if you have a large number of items in the IList. A resolution to this is to do the middle calculation a bit differently using a subtraction instead; Middle = Lower + (Upper - Lower) / 2;

    Bentley also warned in Programming Pearls that while the binary search algorithm was published in 1946 and the first correct implementation wasn't published until 1962.

    http://en.wikipedia.org/wiki/Binary_search#Numerical_difficulties

提交回复
热议问题