Binary search: Difference between revisions

m
→‎{{header|Picat}}: Added subsections, added {{out}}
m (→‎{{header|Picat}}: Added subsections, added {{out}})
Line 5,077:
 
=={{header|Picat}}==
% ===Iterative version===
<lang Picat>go =>
A = [2, 4, 6, 8, 9],
TestValues = [2,1,8,10,9,5],
 
println("iterative:"),
foreach(Value in TestValues)
test(binary_search,A, Value)
end,
test(binary_search,[1,20,3,4], 5), % unsorted array
nl,
println("recursive:"),
foreach(Value in TestValues)
test(binary_search_rec,A, Value)
end,
test(binary_search_rec,[1,20,3,4], 5), % unsorted array
nl.
 
Line 5,106 ⟶ 5,100:
end.
 
% Iterative version
binary_search(A, Value) = V =>
V1 = 0,
Line 5,130 ⟶ 5,123:
end,
V = V1.
</lang>
 
{{out}}
% Recursive version
<pre>A: [2,4,6,8,9] Value:2 Ret: 1: The value 2 is found at position 1.
binary_search_rec(A, Value) = Ret =>
A: [2,4,6,8,9] Value:1 Ret: 0: The value 1 is not in the array.
A: [2,4,6,8,9] Value:8 Ret: 4: The value 8 is found at position 4.
A: [2,4,6,8,9] Value:10 Ret: 0: The value 10 is not in the array.
A: [2,4,6,8,9] Value:9 Ret: 5: The value 9 is found at position 5.
A: [2,4,6,8,9] Value:5 Ret: 0: The value 5 is not in the array.
A: [1,20,3,4] Value:5 Ret: -1: The array is not sorted.
</pre>
 
% ===Recursive version===
<lang Picat>binary_search_rec(A, Value) = Ret =>
Ret = binary_search_rec(A,Value, 1, A.length).
 
Line 5,145 ⟶ 5,149:
end,
Mid = Mid1.</lang>
 
Output:
<pre>iterative:
A: [2,4,6,8,9] Value:2 Ret: 1: The value 2 is found at position 1.
A: [2,4,6,8,9] Value:1 Ret: 0: The value 1 is not in the array.
A: [2,4,6,8,9] Value:8 Ret: 4: The value 8 is found at position 4.
A: [2,4,6,8,9] Value:10 Ret: 0: The value 10 is not in the array.
A: [2,4,6,8,9] Value:9 Ret: 5: The value 9 is found at position 5.
A: [2,4,6,8,9] Value:5 Ret: 0: The value 5 is not in the array.
A: [1,20,3,4] Value:5 Ret: -1: The array is not sorted.
 
recursive:
A: [2,4,6,8,9] Value:2 Ret: 1: The value 2 is found at position 1.
A: [2,4,6,8,9] Value:1 Ret: 0: The value 1 is not in the array.
A: [2,4,6,8,9] Value:8 Ret: 4: The value 8 is found at position 4.
A: [2,4,6,8,9] Value:10 Ret: 0: The value 10 is not in the array.
A: [2,4,6,8,9] Value:9 Ret: 5: The value 9 is found at position 5.
A: [2,4,6,8,9] Value:5 Ret: 0: The value 5 is not in the array.
A: [1,20,3,4] Value:5 Ret: -1: The array is not sorted.</pre>
 
=={{header|PicoLisp}}==
495

edits