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
35
02_selection_sort/PowerShell/01_selection_sort.ps1
Normal file
35
02_selection_sort/PowerShell/01_selection_sort.ps1
Normal file
@@ -0,0 +1,35 @@
|
||||
# Finds the smallest value in an array
|
||||
function Find-GRKSmallest
|
||||
{
|
||||
param ($arr)
|
||||
# Stores the smallest value
|
||||
$smallest = $arr[0]
|
||||
# Stores the index of the smallest value
|
||||
$smallest_index = 0
|
||||
0 .. ($arr.count - 1) | ForEach-Object {
|
||||
if ($arr[$_] -lt $smallest) {
|
||||
$smallest_index = $_
|
||||
$smallest = $arr[$_]
|
||||
}
|
||||
}
|
||||
return $smallest_index
|
||||
}
|
||||
|
||||
# Sort array
|
||||
function Sort-GRKSelection
|
||||
{
|
||||
param ($arr)
|
||||
$newArr = New-Object System.Collections.Generic.List[System.Object]
|
||||
1 .. $arr.count | ForEach-Object {
|
||||
# Finds the smallest element in the array and adds it to the new array
|
||||
$smallest = Find-GRKSmallest $arr
|
||||
$newArr.Add($arr[$smallest])
|
||||
$arr.RemoveAt($smallest)
|
||||
}
|
||||
return $NewArr
|
||||
}
|
||||
|
||||
# Can't use a default "@()" range notation as it creates static arrays
|
||||
$arr = New-Object System.Collections.Generic.List[System.Object]
|
||||
$arr.AddRange((5, 3, 6, 2, 10))
|
||||
Sort-GRKSelection $arr
|
||||
Reference in New Issue
Block a user