![]() |
General Programming »
Algorithms & Recipes »
Algorithms
Intermediate
VB.NET Code Package: Bubble SortBy George B GilbertBubble sort that stops when sorting is done, and has an optional second, string array sorted with the main array. |
VB, Windows, .NET, Visual Studio, Dev
|
|
Advanced Search Add to IE Search |
|
|
|
||||||||||||||||

Demo project
Use this bubble sort library to repeat a procedure that sorts an array of any data type in either ascending or descending sequence. Sorting ends as soon as the array is in the correct sequence. The procedure has an optional second, string array parameter that allows you to sort a second array based on the data in the main array. The second array provides a handy way, for example, to sort the keys to objects in a collection based on one of the properties of the objects in the collection. Each time the BubbleSort sub is called, you can include or exclude the 0th element of both the main and the second arrays in the sort.
The code is available in a package file for Double Text users, as well as in a demo project for non-Double Text users.
The Bubble Sort (BST) library consists of two source files (.DbC) and an overview (.DbO). One source file is the BubbleSort procedure; the other is for generating calls to the procedure.
The BST source files generate fully commented code that is ready to compile:
Option Strict On.
Region statements are included. The library is ready to go. Repeat the code as per the following instructions whenever you need a ready to compile copy. (If you don't like the way I've set up the source files, change them in the edit window.)
Each time you need a copy of the bubble sort procedure, follow these steps in Double Text:
string, date, integer, long, double, etc.) and then click OK (or press Enter).
The sub source code is now on the clipboard. If you would like to review the code, press F4. After the sub has been repeated, add it to your project:
Each time you need a call to the bubble sort, follow these steps in Double Text:
After the call statement has been repeated, add it to your project:
All of the above instructions for using the library are in the library overview. Click on the Float button in the Double Text main window whenever you need a refresher. (If you change the source file, don't forget to reflect those changes in the overview.)
Download and unzip the demo project. Open the solution in Visual Studio. When you need this code, use whichever tools you prefer to make a copy of the appropriate code, and then make any needed modifications.
There are several possible variations of the bubble sort sub. Take the number of possible data types for the main array and double it for ascending and descending sequence. I repeated an ascending integer sort for the demo project since that is probably an often used combination. When preparing a copy of the bubble sort procedure for any other combination of array data type and/or sort sequence, you will have to work your way through the code to find all occurrences of the main array data type, as well as the tests that determine the ascending or descending sequence. If creating a bubble sort for dates, you will also have to modify the two If statements that test array elements for seniority from simple tests of greater than or less then to appropriate DateDiff statements
You might also want to find and change the following in the BubbleSort, SwitchValues, and SwitchStrings subs, either before or after you paste the code into your project:
Region statements, delete them.
This version of the BubbleSort sub is an ascending sort of an integer array. Add this sub to a project right after you start the project. Place the sub in a module for global scope:
#Region " BubbleSort "
#Region " ... BubbleSort sub "
Public Sub BubbleSort(ByRef arrayBeingSorted() As Integer, _
Optional ByRef tagArray() As String = Nothing, _
Optional ByVal includeZero As Boolean = True)
'----------------------------------------------------------------------
' Sort an array into ascending sequence (works best on arrays with 1000
' elements or less).
' Pass: arrayBeingSorted Self explanatory (when a string array,
' the sort is case sensitive)
' tagArray Optional second array of strings that,
' when passed, will be reordered in concert
' with the array being sorted (the tagArray
' must have the same number of elements as
' the array being sorted)
' includeZero True = Include 0 element in sort
' False = Do not include 0 element in sort
' Return: arrayBeingSorted In prescribed sequence
' tagArray When included, reordered to match the
' arrayBeingSorted
'----------------------------------------------------------------------
' Date Developer Comments
' ---------- -------------------- ------------------------------------
' 03/04/2006 G Gilbert Original code
'----------------------------------------------------------------------
'------------------------------------------------
' Set the lower and upper bounds of the sort
'------------------------------------------------
Dim firstElement As Integer
Dim lastElement As Integer
If Not includeZero Then
firstElement = 1
End If
lastElement = arrayBeingSorted.GetUpperBound(0)
'------------------------------------------------
' Determine if an array of tags was passed. When
' passed, the length of the tag array must be the
' same as the array being sorted. If they are not
' the same length, the tag array is not sorted.
'------------------------------------------------
Dim sortTags As Boolean
If Not IsNothing(tagArray) Then
If tagArray.GetUpperBound(0) = lastElement Then
sortTags = True
End If
End If
'------------------------------------------------
' Arrays with none, or only one element don't
' need sorting
'------------------------------------------------
If lastElement <= firstElement Then
Exit Sub
End If
'------------------------------------------------
' A bubble sort will not work on arrays of less
' than 3 elements. When there are only two
' elements, do a quick comparison and, if needed,
' swap the array elements.
'------------------------------------------------
If (lastElement - firstElement + 1) = 2 Then
If arrayBeingSorted(firstElement) >
arrayBeingSorted(lastElement) Then
SwitchValues(arrayBeingSorted(firstElement), _
arrayBeingSorted(lastElement))
If sortTags Then
SwitchStrings(tagArray(firstElement), _
tagArray(lastElement))
End If
End If
Exit Sub
End If
'------------------------------------------------
' Do the bubble sort (stop the sort when a pass
' is made with no swaps)
'------------------------------------------------
Dim noSwapMade As Boolean
For passNumber As Integer = 0 To lastElement
noSwapMade = True
For nextPointer As Integer = 0 To
(lastElement - 1) - passNumber
If arrayBeingSorted(nextPointer) >
arrayBeingSorted(nextPointer + 1) Then
SwitchValues(arrayBeingSorted(nextPointer), _
arrayBeingSorted(nextPointer + 1))
If sortTags Then
SwitchStrings(tagArray(nextPointer), _
tagArray(nextPointer + 1))
End If
noSwapMade = False
End If
Next
If noSwapMade Then
Exit For
End If
Next
End Sub
#End Region
#Region " ... SwitchValues sub "
Private Sub SwitchValues(ByRef Value1 As Integer, _
ByRef Value2 As Integer)
'-----------------------------------------------------------
' Swap the two passed values
'
' Pass: Value1 The first value
' Value2 The second value
' Return: Value1 What used to be in Value2
' Value2 What used to be in Value1
'-----------------------------------------------------------
' Date Developer Comments
' ---------- -------------------- -------------------------
' 03/04/2006 G Gilbert Original code
'-----------------------------------------------------------
Dim TempValue As Integer
TempValue = Value1
Value1 = Value2
Value2 = TempValue
End Sub
#End Region
#Region " ... SwitchStrings sub "
Private Sub SwitchStrings(ByRef Value1 As String, _
ByRef Value2 As String)
'-----------------------------------------------------------
' Swap the two passed strings
'
' Pass: Value1 The first value
' Value2 The second value
' Return: Value1 What used to be in Value2
' Value2 What used to be in Value1
'-----------------------------------------------------------
' Date Developer Comments
' ---------- -------------------- -------------------------
' 03/04/2006 G Gilbert Original code
'-----------------------------------------------------------
Dim TempValue As String
TempValue = Value1
Value1 = Value2
Value2 = TempValue
End Sub
#End Region
#End Region
A bubble sort is best used on arrays of three or more, and up to 1,000 elements. The procedure in this library protects against trying to sort arrays that are too small. Should an array of less than three elements be passed to this bubble sort, the procedure will handle the array correctly.
A bubble sort is certainly nothing new. There are, however, several variations on this simple theme when the array data type and sort sequence are considered. That is the primary reason I set up this library. Being able to repeat a bug free sort routine with any array data type and sort sequence in seconds are, in my opinion, very good things. Having the second, string array, plus the option to exclude the 0th array element, just makes this library much more flexible, and, therefore, much more useful.
You may use the Double Text library and all the code offered in this article any way you choose without restriction.
Under no circumstances, and under no legal theory, tort, contract, or otherwise, will George Gilbert (hereafter referred to as "software author") or his licensors, be liable to the user of the Double Text library and all code offered in this article (hereafter referred to collectively as "article code"), for any damages, including any lost profits, lost data, or other indirect, special, incidental, or consequential damages, arising out of the use or inability to use the article code, and data or information supplied, even if the software author, his licensors or authorized dealer have been advised of the possibility of such damages, or for any claim by any other party.
| You must Sign In to use this message board. | |||||||||||||||
|
|||||||||||||||
|
|||||||||||||||
|
|||||||||||||||
|
|||||||||||||||
General
News
Question
Answer
Joke
Rant
Admin
|
PermaLink |
Privacy |
Terms of Use
Last Updated: 8 Mar 2006 Editor: Rinish Biju |
Copyright 2006 by George B Gilbert Everything else Copyright © CodeProject, 1999-2009 Web20 | Advertise on the Code Project |