Skip to content

Commit c5c2563

Browse files
itadderegonSchiele
authored andcommitted
Powershell Version of Binary Search (egonSchiele#15)
* Powershell Version of Binary Search
1 parent e4b95bd commit c5c2563

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
#Binary Search in Powershell / .net
2+
#Author ITAdder (Justino Garcia)
3+
#clear screen after every run.
4+
clear-host
5+
6+
$mylist = (1,3,5,7,9);
7+
8+
9+
function Search-Binary
10+
{
11+
#[CmdletBinding()]
12+
#[Alias()]
13+
#[OutputType([int])]
14+
Param
15+
(
16+
# numeric lists
17+
[Parameter(Mandatory=$true,
18+
ValueFromPipelineByPropertyName=$true,
19+
Position=0)]
20+
21+
[int[]]$list,
22+
23+
# $item will then be passed between calls as you reduce your list
24+
25+
$item
26+
)
27+
28+
[int] $low = 0;
29+
$high = $list.Length -1;
30+
31+
while ($low -lt $high) {
32+
33+
$mid = ($low + $high) / 2;
34+
35+
$guess = $list[$mid];
36+
37+
38+
if ($guess -eq $item) {
39+
40+
return $mid;
41+
}
42+
43+
if ($guess -gt $item)
44+
{
45+
$high = ($mid -1);
46+
}
47+
48+
else{
49+
50+
$low = $mid + 1
51+
}
52+
return $null;
53+
}
54+
55+
56+
}
57+
58+
Search-Binary -list $mylist -item 2

0 commit comments

Comments
 (0)