This pseudocode is an implementation of the Bubble Sort algorithm with a slight optimization.
Let’s go
step-by-step to explain what it does:
DECLARE myList : ARRAY[0:8] OF INTEGER
DECLARE upperBound : INTEGER
DECLARE lowerBound : INTEGER
DECLARE index : INTEGER
DECLARE swap : BOOLEAN
DECLARE temp : INTEGER
DECLARE top : INTEGER
upperBound ← 8
lowerBound ← 0
top ← upperBound
REPEAT
FOR index = lowerBound TO top - 1
Swap ← FALSE
IF myList[index] > myList[index + 1]
THEN
temp ← myList[index]
myList[index] ← myList[index + 1]
myList[index + 1] ← temp
swap ← TRUE
ENDIF
NEXT
top ← top -1
UNTIL (NOT swap) OR (top = 0)
🔷 Purpose:
To sort a list of integers (myList) in ascending order using the Bubble Sort algorithm.
🔶 Variable Declarations:
myList : ARRAY[0:8] OF INTEGER → List of 9 integers to be sorted
upperBound ← 8 → Highest index in the array
lowerBound ← 0 → Lowest index in the array
top ← upperBound → Controls the last element checked in each pass
index → Loop counter
swap : BOOLEAN → Tracks whether a swap occurred during a pass
temp : INTEGER → Temporary variable for swapping
1
🔁 Sorting Process – REPEAT loop:
The algorithm repeatedly passes through the list, swapping adjacent elements if they are out of order.
Step-by-step breakdown:
1. Initialize top to upperBound (i.e., the last index of the array).
2. Repeat the sorting pass until either:
o No swaps are made in a pass (NOT swap), which means the list is already sorted.
o Or top = 0, which means only one element is left (no need to sort).
3. Inside each pass:
o Start from the first index (lowerBound) to top - 1.
o If the current element is greater than the next one:
Swap them using temp.
Set swap ← TRUE to indicate a change was made.
4. After each complete pass:
o Decrease top by 1, since the largest element has "bubbled up" to its correct position and
doesn’t need to be checked again.
✅ Key Features:
Bubble Sort Algorithm: Classic sorting method that compares adjacent elements.
Optimization:
o swap ← FALSE at the start of each pass.
o The loop stops early if a pass makes no swaps (NOT swap), indicating the list is sorted.
🔚 Termination:
The loop ends when the list is sorted (no swaps in a pass) or when only one item remains to be sorted.
2
Module Module1
Sub Main()
Dim myList() As Integer = {5, 3, 8, 2, 1, 4, 7, 6, 9}
Dim upperBound As Integer = 8
Dim lowerBound As Integer = 0
Dim index As Integer
Dim swap As Boolean
Dim temp As Integer
Dim top As Integer
top = upperBound
[Link]("Original List:")
PrintArray(myList)
Do
swap = False
For index = lowerBound To top - 1
If myList(index) > myList(index + 1) Then
' Swap the values
temp = myList(index)
myList(index) = myList(index + 1)
myList(index + 1) = temp
swap = True
End If
Next
top = top - 1
Loop Until (Not swap) Or (top = 0)
[Link](vbCrLf & "Sorted List:")
PrintArray(myList)
[Link]()
End Sub
Sub PrintArray(ByVal arr() As Integer)
For i As Integer = 0 To [Link] - 1 'For Each item In arr
[Link](i & " ")
Next
[Link]()
End Sub
End Module