Click here to Skip to main content
5,788,212 members and growing! (19,566 online)
Email Password   helpLost your password?
General Programming » Algorithms & Recipes » Algorithms     Intermediate

VB.NET Code Package: Bubble Sort

By George B Gilbert

Bubble 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

Posted: 17 Jan 2006
Updated: 8 Mar 2006
Views: 50,271
Bookmarked: 21 times
Announcements
Loading...



Search    
Advanced Search
Sitemap
13 votes for this Article.
Popularity: 2.87 Rating: 2.58 out of 5
4 votes, 30.8%
1
2 votes, 15.4%
2
1 vote, 7.7%
3
2 votes, 15.4%
4
4 votes, 30.8%
5

Demo project

Contents

Introduction

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.

Double Text users

Library overview

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:

  • The code was written with Option Strict On.
  • The repeated code has been tested multiple times.
  • The code is fully commented.
  • Region statements are included.

Unwrapping the library

  1. Download and unzip the package file. The package file is named Bubble Sort.DbP.
  2. Unwrap the package in Double Text (File | Library Exchange | Unwrap). Save the library in an empty folder.

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.)

Using the library

Repeating the sub procedure

Each time you need a copy of the bubble sort procedure, follow these steps in Double Text:

  1. In the main window, press F12 and browse to the BST library.
  2. Click on the "Sub Procedure" title.
  3. In the Sort Sequence window, select either Ascending or Descending sort sequence, and then click OK.
  4. In the first If Statement window, select either Ascending or Descending sequence (same as the Sort Sequence step) for either non-date variable types or dates, and then click OK.
  5. In the second If Statement window, select the same option as you did in the first If Statement window, and then click OK.
  6. For the "Array data type" prompt, enter the data type of the main array (e.g. string, date, integer, long, double, etc.) and then click OK (or press Enter).
  7. For the "Name of developer" prompt, enter your name and click OK (or press Enter). You can also just press Enter to accept the default name (mine).
  8. In the reminder window, click OK.

    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:

    1. In Visual Studio, either open an existing module, or add a module.
    2. Place the insertion cursor where you want to add the bubble sort sub in the module.
    3. Press Ctrl^V.

Repeating the call statement

Each time you need a call to the bubble sort, follow these steps in Double Text:

  1. In the main window, press F12 and browse to the BST library.
  2. Click on the "Call Statement" title.
  3. In the Call Parameters window, select the item that matches the parameter mix for this call to the sort (passing/not passing a second string array; including/not including the 0th element in the sort) and click OK.
  4. At the "Name of array being sorted" prompt, enter the name of the array being sorted (without parenthesis) and click OK (or press Enter).
  5. If a second array is being passed, at the "Second array name" prompt, enter the name of the second, string array (without parenthesis), and click OK (or press Enter).

    After the call statement has been repeated, add it to your project:

    1. In Visual Studio, place the insertion cursor where you want to add the call statement.
    2. Press Ctrl^V.

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.)

Non-Double Text users

Demo project summary

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:

  • If you don't want the Region statements, delete them.
  • Change the date the code is added to your project.
  • Change the name of the developer.

BubbleSort sub code

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

Points of interest

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.

Conclusion

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.

Licensing and limitation of liability

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.

History

  • 3/4/2006
    • While looking through links for people who had visited my web site, I came across one visitor who had done a search for a VB.NET bubble sort for dates. Since the bubble sort in my original article didn't include a date variable type option, I concluded that this was rude of me and a condition that needed to be rectified. Ergo, the Double Text sort package offered by this article has been modified so that when you repeat the sub procedure you can create a bubble sort that will sort an array of dates into ascending or descending sequence.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

George B Gilbert


Click here to see a complete list of my articles.
Occupation: Software Developer
Location: United States United States

Other popular Algorithms & Recipes articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 2 of 2 (Total in Forum: 2) (Refresh)FirstPrevNext
GeneralThanksmembersoheilajoon4:10 4 Jan '09  
GeneralRe: ThanksmemberGeorge B Gilbert7:25 4 Jan '09  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin 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
Web11 | Advertise on the Code Project