How to resolve the algorithm Sorting algorithms/Cocktail sort step by step in the VBA programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Sorting algorithms/Cocktail sort step by step in the VBA programming language
Table of Contents
Problem Statement
The cocktail shaker sort is an improvement on the Bubble Sort. The improvement is basically that values "bubble" both directions through the array, because on each iteration the cocktail shaker sort bubble sorts once forwards and once backwards. Pseudocode for the algorithm (from wikipedia):
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Sorting algorithms/Cocktail sort step by step in the VBA programming language
Source code in the vba programming language
Function cocktail_sort(ByVal s As Variant) As Variant
Dim swapped As Boolean
Dim f As Integer, t As Integer, d As Integer, tmp As Integer
swapped = True
f = 1
t = UBound(s) - 1
d = 1
Do While swapped
swapped = 0
For i = f To t Step d
If Val(s(i)) > Val(s(i + 1)) Then
tmp = s(i)
s(i) = s(i + 1)
s(i + 1) = tmp
swapped = True
End If
Next i
'-- swap to and from, and flip direction.
'-- additionally, we can reduce one element to be
'-- examined, depending on which way we just went.
tmp = f
f = t + (d = 1)
t = tmp + (d = -1)
d = -d
Loop
cocktail_sort = s
End Function
Public Sub main()
Dim s(9) As Variant
For i = 0 To 9
s(i) = CStr(Int(1000 * Rnd))
Next i
Debug.Print Join(s, ", ")
Debug.Print Join(cocktail_sort(s), ", ")
End Sub
You may also check:How to resolve the algorithm Sexy primes step by step in the Java programming language
You may also check:How to resolve the algorithm Apply a digital filter (direct form II transposed) step by step in the Phixmonti programming language
You may also check:How to resolve the algorithm AVL tree step by step in the TypeScript programming language
You may also check:How to resolve the algorithm Short-circuit evaluation step by step in the PowerShell programming language
You may also check:How to resolve the algorithm Number reversal game step by step in the JavaScript programming language