Binary search: Difference between revisions

Content added Content deleted
m (→‎{{header|Sidef}}: updated code)
Line 1,662: Line 1,662:
Both solutions use ''sublists'' and a tracking offset in preference to "high" and "low".
Both solutions use ''sublists'' and a tracking offset in preference to "high" and "low".
====Recursive Solution====
====Recursive Solution====
<lang groovy>def binSearchR
<lang groovy>
binSearchR = { a, target, offset=0 ->
def binSearchR
//define binSearchR closure.
def n = a.size()
binSearchR = { a, key, offset=0 ->
def m = n.intdiv(2)
def m = n.intdiv(2)
def n = a.size()
a.empty \
a.empty \
? ["insertion point": offset] \
? ["The insertion point is": offset] \
: a[m] > target \
: a[m] > key \
? binSearchR(a[0..<m], target, offset) \
? binSearchR(a[0..<m],key, offset) \
: a[m] < target \
: a[m] < target \
? binSearchR(a[(m + 1)..<n], target, offset + m + 1) \
? binSearchR(a[(m + 1)..<n],key, offset + m + 1) \
: [index: offset + m]
: [index: offset + m]
}
}</lang>
</lang>

====Iterative Solution====
====Iterative Solution====
<lang groovy>def binSearchI = { aList, target ->
<lang groovy>def binSearchI = { aList, target ->