header
header Register : : Login header
header
divider
menuleft
menuright
submenu
left

[August 25th, 2008] Check the home page regarding PowerShell related news from a brand new sponsor: Idera

Subject: The classic binary search algorithm
Prev Next
You are not authorized to post a reply.

Author Messages
kscrissUser is Offline
Power User
Power User
Posts:122


02/21/2008 10:00 AM  
#
#
#      \\\\ ////
#     \\  - -  //
#         @ @
# ---oOOo-( )-oOOo---
#
# PowerShell Script: BinarySearch.ps1
# Author: Kevin Criss
#
# This is the classic binary search algorithm implemented in the Powershell Programming language.
# This algorithm is the heart and soul of any respectable search engine.
#
# Its also a very efficient way to search an array! Requires the array being searched to be pre-sorted in the sequence of your search key.
# This pre-sorting or pre-ordering the array in search-key sequence is a requirement of the binary search algorithm!
#
# How does it work and why do they call it the Binary Search, are we manipulating bits 1 and 0? No, were not doing anything with bits just pieces.
# A binary search always cuts the array into two pieces at the middle point. Then it checks the item being searched for against the contents at
# the middle point. If the contents at the middle point is greater than the item being search, the current middle point becomes the new high point
# and the array is cut in half again and re-tested. If the contents at the middle point is less than the item being searched, the current middle
# point becomes the new low point and the array is cut in half again and re-tested. This cutting in half and adjusting either the high point or the
# low point is repeated until the item is found or the low point and the high point converge. This is much faster then sequentially searching an
# entire array. 

# Additional Reference: 
# http://googleresearch.blogspot.com/2006/06/extra-extra-read-all-about-it-nearly.html 
# Thank you Mr. Bloch for sharing the patch to this classic algorithm via your Google Research Blog. I have incorporated the new formula you
# are reporting for calculating the $script:MiddlePoint into this routines. 
#

################################################
# Function: PowerShell Binary Search Algorithm #
################################################
#
function BinarySearch
{
   Param ($YourOrderedArray, $ItemSearched)
   [int] $LowIndex = 0
   [int] $HigIndex = $YourOrderedArray.length - 1
   while ($LowIndex -le $HigIndex)
       {
#        [int]$script:MiddlePoint = ($LowIndex + $HigIndex) / 2
         [int]$script:MiddlePoint = $LowIndex + (($HigIndex - $LowIndex/ 2)
         $InspectedValue = $YourOrderedArray[$script:MiddlePoint].YourObjectSearched
         If ($InspectedValue -lt $ItemSearched)
             {
                $LowIndex = $script:MiddlePoint + 1
             }
         Elseif ($InspectedValue -gt $ItemSearched)
             {
                $HigIndex = $script:MiddlePoint - 1
             }
         Else
             {
                $script:ItemFound = $True
                return
             }
      }
    $script:ItemFound = $False
    $script:MiddlePoint = -($LowIndex + 1)
    return
}
################################################
# Main Routine                                 #
################################################
# Usage:
BinarySearch $MySearchKey  $MyArray_Presorted_in_searchkey_Sequence
#
#      Returns ($script:ItemFound = $True and the $script:MiddlePoint indexing the location of the item)
#         or
#      Returns ($script:ItemFound = $False
#      and $script:MiddlePoint equal to the negative value of $YourOrderedArray.length +1)

My blog: http://blogs.powershellcentral.com/kscriss/
kscrissUser is Offline
Power User
Power User
Posts:122


02/21/2008 11:12 AM  
Opps, I think its called this way instead. I have it backwards above.

BinarySearcy $MyArray_Presorted_in_Searchkey_Sequence $MySearchKey

$Mysearchkey it the item that I am looking to find inside the $MyArray_Presorted_in_Searchkey_Sequence.

My blog: http://blogs.powershellcentral.com/kscriss/
kscrissUser is Offline
Power User
Power User
Posts:122


03/10/2008 11:19 AM  
This rewrite is much better it does not require scoped variables.

function BinarySearch
   {
       Param ( $YourOrderedArray, $ItemSearched)
       [int] $LowIndex = 0
       [int] $HighIndex = $YourOrderedArray.length - 1
       while ($LowIndex -le $HighIndex)
          {
             [int]$MiddlePoint = $LowIndex + (($HighIndex - $LowIndex) / 2)
             $InspectedValue = $YourOrderedArray[$MiddlePoint].name
#            #################################################.name A.K.A. $ItemSearched because its an object array.
             If ($InspectedValue -lt $ItemSearched)
                 {
                    $LowIndex = $MiddlePoint + 1
                    IF ($LowIndex -eq $HighIndex) 
                       {
                          $ItemFoundSwitch = $False
                          $ItemFoundIndex = ($HighIndex*-1)
#                         "LowIndex $LowIndex"          | Out-Host
#                         "HighIndex $HighIndex"        | Out-Host 
#                         "Item found $ItemFoundSwitch" | Out-Host
#                         "Item Index $ItemFoundIndex"  | Out-Host     
                       }
                 }
             Elseif ($InspectedValue -gt $ItemSearched)
                 {
                    $HighIndex = $MiddlePoint - 1
                    IF ($LowIndex -eq $HighIndex) 
                       {
                          $ItemFoundSwitch = $False
                          $ItemFoundIndex = ($HighIndex*-1)
#                         "LowIndex $LowIndex"          | Out-Host
#                         "HighIndex $HighIndex"        | Out-Host 
#                         "Item found $ItemFoundSwitch" | Out-Host
#                         "Item Index $ItemFoundIndex"  | Out-Host     
                       }
                 }
             Elseif ($InspectedValue -eq $ItemSearched)
                 {
                     $LowIndex++ # Break Out else infinite loop
                     $ItemFoundSwitch = $True 
                     $ItemFoundIndex = $MiddlePoint
#                    "LowIndex $LowIndex"                 | Out-Host
#                    "HighIndex $HighIndex"               | Out-Host 
#                    "Item Found $ItemFoundSwitch"        | Out-Host
#                    "Item Index $ItemFoundIndex"         | Out-Host 
#                    Return
                 }
          }
      $SearchResults = New-Object psobject
      $SearchResults | Add-Member noteproperty ItemFoundSwitch $ItemFoundSwitch
      $SearchResults | Add-Member noteproperty ItemFoundIndex  $ItemFoundIndex
      write $SearchResults
   }   
#
#    

And it would be called like this.
<code>
$B = Get-WmiObject win32_service -comp $Server
$Results_Array_B = BinarySearch $B $ServiceName
</code>

My blog: http://blogs.powershellcentral.com/kscriss/
You are not authorized to post a reply.
Forums > Using PowerShell > General PowerShell > The classic binary search algorithm



ActiveForums 3.7
right
   
footer Sponsored by Quest Software • SAPIEN Technologies • ShellTools, LLC • Microsoft Windows Server 2008 footer
footer