Skip to content

Instantly share code, notes, and snippets.

@Calvindd2f
Last active September 22, 2024 13:38
Show Gist options
  • Select an option

  • Save Calvindd2f/513045508c37d096b2dc3cd1e998e87d to your computer and use it in GitHub Desktop.

Select an option

Save Calvindd2f/513045508c37d096b2dc3cd1e998e87d to your computer and use it in GitHub Desktop.
<#
.SYNOPSIS
Sorts an array using the Bubble Sort algorithm.
.DESCRIPTION
Sorts the input array in ascending order using the Bubble Sort algorithm.
.PARAMETER s
The sequence of values to be sorted. Supports numbers and strings.
.OUTPUTS
Sorted array.
.EXAMPLE
$s = 4, 15, "delta", 2, -31, 0, "alfa", 19, "gamma", 2, 13, "beta", 782, 1
Write-Output "Before Sorting:"
Write-Output (bubble_sort $s)
.LINK
https://github.com/Calvindd2f
#>
# Variable Declaration
<#
readonly
######################################################
########## INPUT
######################################################
$s = @();
######################################################
########## OUTPUT
######################################################
$activityOutput = [pscustomobject]@{
success = $true;
error = $null;
debug = $null;
output = $null;
};
#>
function Verify-Activity {
param(
[Array]$s
)
$activityOutput = [pscustomobject]@{
success = $true;
error = $null;
debug = $null;
output = $null;
}
try {
if (-not $s) {
throw "Input array cannot be null or empty."
}
$activityOutput.output = $true
}
catch {
$activityOutput.success = $false
$activityOutput.error = $_.Exception.Message
$activityOutput.debug = $_.Exception
}
return $activityOutput
}
function Main-Activity {
param(
[Array]$s
)
[object]$tmp
[bool]$changed
for ($j = $s.Length - 1; $j -gt 0; $j--) {
$changed = $false
for ($i = 0; $i -lt $j; $i++) {
if ($s[$i] -gt $s[$i + 1]) {
$tmp = $s[$i]
$s[$i] = $s[$i + 1]
$s[$i + 1] = $tmp
$changed = $true
}
}
if (-not $changed) { break }
}
return $s
}
function Execute-Activity {
param(
[Array]$s
)
$activityOutput = [pscustomobject]@{
success = $true;
error = $null;
debug = $null;
output = $null;
}
try {
# Verify input
$verifyResult = Verify-Activity -s $s
if (-not $verifyResult.success) {
throw $verifyResult.error
}
# Perform sorting
$activityOutput.output = Main-Activity -s $s
}
catch {
$activityOutput.success = $false
$activityOutput.error = $_.Exception.Message
$activityOutput.debug = $_.Exception
}
return $activityOutput
}
# Example of execution
$s = 4, 15, "delta", 2, -31, 0, "alfa", 19, "gamma", 2, 13, "beta", 782, 1
Write-Output "Before Sorting:"
Write-Output $s
# Execution
$result = Execute-Activity -s $s
# Output results
if ($result.success) {
Write-Output "After Sorting:"
$result.output | ForEach-Object { Write-Output $_ }
} else {
Write-Error $result.error
}
@Calvindd2f

Copy link
Copy Markdown
Author

powershell-elitism

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment