From: mame@... Date: 2015-01-12T12:46:49+00:00 Subject: [ruby-core:67540] [ruby-trunk - Feature #10730] Implement Array#bsearch_index Issue #10730 has been updated by Yusuke Endoh. > Why do we have Array#bsearch? Just because matz wanted it: https://redmine.ruby-lang.org/issues/4766#note-2 Personally, I don't think Array#bsearch is necessarily required. Range#bsearch is more general and powerful. However, Array#bsearch is indeed useful for typical use case of binary search, and it provides a similar API to C's BSEARCH(3). In this sense, Array#bsearch is considered as a handy short cut for Range#bsearch. I'm neutral to Array#bsearch_index, but how handy is it? Symmetry/consistency is not a good reason for Ruby design. http://stackoverflow.com/questions/23481725/using-bsearch-to-find-index-for-inserting-new-element-into-sorted-array shows a somewhat reasonable use case, but the insert takes O(n). Is it okay? When you have to modify the array that is used for bsearch, rbtree gem might be a better choice; both search and insert take O(log n). -- Yusuke Endoh ---------------------------------------- Feature #10730: Implement Array#bsearch_index https://bugs.ruby-lang.org/issues/10730#change-50954 * Author: Radan Skori�� * Status: Open * Priority: Normal * Assignee: ---------------------------------------- We currently have Array#bsearch but no Array#bsearch_index and to me it seems that violates the principle of least surprise, especially when we consider the other combinations of existing methods that find either an element or it���s index. For example: the method would be very useful when needing to slice out a part of a sorted array. It would allow very quick location of the indices of the beginning and end of the segment. A quick google of ���ruby bsearch_index��� reveals that I am not the only one that needed and expected that function to exist: http://stackoverflow.com/questions/23481725/using-bsearch-to-find-index-for-inserting-new-element-into-sorted-array http://stackoverflow.com/questions/8672472/is-there-a-built-in-binary-search-in-ruby https://github.com/tyler/binary_search#usage The very good thing is that we can get that method almost for free since the current implementation of bsearch internally finds the index and then looks up the actual element. I have opened a PR on the github mirror that adds bsearch_index in what seems to me the simplest way possible: https://github.com/ruby/ruby/pull/813 . I changed the bsearch implementation into bsearch_index and based the bsearch on it. Please Note: The diff is deceptively large, if you look carefully you will notice that the change is actually small and the actual binary search algorithm remained completely intact. I have kept the behaviour documentation on bsearch and simply referenced it from bsearch_index to minimize the documentation changes. -- https://bugs.ruby-lang.org/