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> |
<lang groovy> |
||
binSearchR |
def binSearchR |
||
//define binSearchR closure. |
|||
⚫ | |||
binSearchR = { a, key, offset=0 -> |
|||
def m = n.intdiv(2) |
def m = n.intdiv(2) |
||
⚫ | |||
a.empty \ |
a.empty \ |
||
? ["insertion point": offset] \ |
? ["The insertion point is": offset] \ |
||
: a[m] > |
: a[m] > key \ |
||
? binSearchR(a[0..<m], |
? binSearchR(a[0..<m],key, offset) \ |
||
: a[m] < target \ |
: a[m] < target \ |
||
? binSearchR(a[(m + 1)..<n], |
? binSearchR(a[(m + 1)..<n],key, offset + m + 1) \ |
||
: [index: offset + m] |
: [index: offset + m] |
||
} |
|||
</lang> |
|||
====Iterative Solution==== |
====Iterative Solution==== |
||
<lang groovy>def binSearchI = { aList, target -> |
<lang groovy>def binSearchI = { aList, target -> |