Tuesday, August 30, 2011

PowerShell: Bubble Sort

As Donald Knuth stated, "the bubble sort seems to have nothing to recommend it, except a catchy name and the fact that it leads to some interesting theoretical problems".
That said, here it is implemented in PowerShell.
Function BubbleSort($arrArray) {
  Do {
    $boolChanged = $false
    for ($i = 0 ; $i -lt $arrArray.length - 1; $i++) {
      if ($arrArray[$i] -gt $arrArray[$i+1]) {
        $arrArray[$i], $arrArray[$i+1] =`
	$arrArray[$i+1], $arrArray[$i]
	$boolChanged = $true
      }
    }
  }
  Until (-not $boolChanged)
  $arrArray
}

No comments: