手动二进制搜索总结

时间:2017-01-08 17:44:23

标签: ruby if-statement recursion binary-search

有人会如此友好地向我解释我如何完成递归二分查找问题?递归方面令我感到困惑。如果可能的话,我希望能解释一下这是做什么的!我想我需要增加一半的'我在if或elsif中的价值,但我不知道它会是什么样子。请建议添加到我目前拥有的代码的方法,而不是重构更简单的东西......至少在开始时!谢谢!

def binary_search(letter, array)
  half = (array.length - 1)/2
  if letter == array[half]
    return half
  end
  if letter > array[half] && letter <= array[-1]
    array = array[half...array.length]
    binary_search(letter, array)
  elsif letter < array[half] && letter >= array[0]
    array = array[0...half]
    binary_search(letter, array)
  else
    nil
  end
end

arr = [:A, :B, :C, :D, :E, :F, :G]
p binary_search(:C, arr)

1 个答案:

答案 0 :(得分:1)

half是问题的一部分。如果lengthhalf,则0将为half,您将&#34;拆分&#34;你的数组在一个完整的数组和一个空数组中:递归永远不会结束。

您还需要保留索引,并在考虑第二个数组时向其添加def binary_search(letter, array, i=0) puts "Been here for #{array} with #{i}" half = array.length / 2 if letter == array[half] return i + half end if letter > array[half] && letter <= array[-1] binary_search(letter, array.drop(half), i + half) elsif letter < array[half] && letter >= array[0] binary_search(letter, array.take(half), i) else nil end end arr = [:A, :B, :C, :D, :E, :F, :G] p binary_search(:C, arr) p binary_search(:G, arr)

Been here for [:A, :B, :C, :D, :E, :F, :G] with 0
Been here for [:A, :B, :C] with 0
Been here for [:B, :C] with 1
2
Been here for [:A, :B, :C, :D, :E, :F, :G] with 0
Been here for [:D, :E, :F, :G] with 3
Been here for [:F, :G] with 5
6

输出

<record id="view_inherit_filter" model="ir.ui.view">
    <field name="name">res.partner.select.inherit</field>
    <field name="model">res.partner</field>
    <field name="inherit_id" ref="base.view_res_partner_filter"/>
    <field name="arch" type="xml">
        <search string="Search Partner">
            <xpath expr="filter[@string='Customers']" position="attributes">
                <attribute name='invisible'>1</attribute> 
            </xpath>
            <filter string="Acheteurs" name="buyer" domain="[('isBuyer','=',1)]" help="Liste Acheteurs" />
            <filter string="Vendeurs" name="seller" domain="[('isSeller','=',1)]" help="Liste Vendeur"/>
            <filter string="Fournisseurs" name="supplier" domain="[('isSupplier','=',1)]" help="Liste Fournisseurs"/>
            <filter string="Intermediares" name="interm" domain="[('isMiddle','=',1)]" help="Liste Intermdiaires"/>
            <filter string="Backoffices" name="back" domain="[('isBackOffice','=',1)]" help="Liste BackOffice"/>
            <separator/>
            <field name="category_id" string="Tag" filter_domain="[('category_id','ilike', self)]"/>
            <field name="user_id"/>
            <field name="parent_id" domain="[('is_company','=',1)]" operator="child_of"/>
        </search>
    </field>
</record>