Please, merge my PowerShell examples for all chapters (#106)
* PowerShell 01_introduction_to_algorithms example * PowerShell 02_selection_sort example * PowerShell 03_recursion examples * PowerShell 04_quicksort examples * PowerShell 05_hash_tables examples * PowerShell 06_breadth-first_search example * PowerShell 07_dijkstras_algorithm example * PowerShell 08_greedy_algorithms example * Powershell 09_dynamic_programming example
This commit is contained in:
committed by
Aditya Bhargava
parent
d7de908a82
commit
06ee65d9e5
@@ -0,0 +1,39 @@
|
||||
function Search-GRKBinary
|
||||
{
|
||||
param ($list, $item)
|
||||
|
||||
# $low and $high keep track of which part of the list you'll search in.
|
||||
$low = 0;
|
||||
$high = $list.Length - 1;
|
||||
|
||||
# While you haven't narrowed it down to one element ...
|
||||
while ($low -le $high)
|
||||
{
|
||||
# ... check the middle element
|
||||
$mid = [int](($low + $high) / 2);
|
||||
$guess = $list[$mid];
|
||||
# Found the item.
|
||||
if ($guess -eq $item)
|
||||
{
|
||||
return $mid;
|
||||
}
|
||||
# The guess was too high.
|
||||
if ($guess -gt $item)
|
||||
{
|
||||
$high = $mid - 1
|
||||
}
|
||||
# The guess was too low
|
||||
else
|
||||
{
|
||||
$low = $mid + 1
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
# Item doesn't exist
|
||||
return $null;
|
||||
}
|
||||
|
||||
$mylist = (1, 3, 5, 7, 9);
|
||||
Search-GRKBinary $mylist 3 # => 1
|
||||
Search-GRKBinary $mylist -1 # => $null
|
||||
Reference in New Issue
Block a user