My Randumb Lief


Bubble Sort in VB6
May 6, 2007, 8:10 pm
Filed under: vb6

Today I wrote a simple bubble sort script in VB6. Very simple to create and I thought I would go over how to make your own.

What is Bubble Sort?
Bubble sorting is one of the easiest sorting algorithms to implement in any programming language. In this example it would most likely be best to use the languages internal sort, mainly because of speed, however whats the harm in understanding how it works?

Code:
Function bubbleSort(dataStr As String)
dataTmp = Split(dataStr, " ")
Do
nCount = nCount + 1
swap = False
For n = LBound(dataTmp) To UBound(dataTmp) - 1
If LCase(dataTmp(n)) > LCase(dataTmp(n + 1)) Then
tmp = dataTmp(n + 1)
dataTmp(n + 1) = dataTmp(n)
dataTmp(n) = tmp
swap = True
End If
Next n
Loop While swap = True
bubbleSort = Join(dataTmp, " ")
End Function

Call the function using:
MsgBox bubbleSort("THIS is a test hahhahahaha what will happen?")

A message box will display: “a hahhahahaha happen? is test THIS what will”

How this works:
The array is populated from dataStr, split on spaces ” “. Then the script gets stuck into a loop until there are no changes to the array, indicated by swap. Inside this do…loop, it further iterates the n loop comparing the current item with the next. If the next item is smaller, they are swapped and the n loop continues. As long as there is a change, the do…loop will fire. Once all changes have been made, the string is reassembled with join using spaces and the value is returned.