Site icon Bernard Aybout's Blog – MiltonMarketing.com

How Does the Bubble Sort Algorithm Work in VB.NET?

Bubble Sort Algorithm Explained with VB.NET Code

Bubble Sort Algorithm Explained with VB.NET Code

Bubble sort is a simple sorting algorithm that is used to arrange a list of elements (like numbers or words) in a specific order, either ascending or descending. It’s called “bubble sort” because smaller elements bubble up to the beginning of the list while larger elements sink to the end, similar to bubbles rising in a liquid.

Here’s a basic explanation of how bubble sort works, suitable for a beginner:

How Bubble Sort Works

  1. Comparing Pairs: Bubble sort starts at the beginning of the list, comparing the first element with the second element. If the first element is larger than the second (in the case of sorting in ascending order), these two elements are swapped.
  2. Continue Comparing: It then moves to the next pair (second and third elements) and repeats the process of comparing and potentially swapping them. This continues for each pair in the list until it reaches the end.
  3. Repeating the Process: Once the end of the list is reached, the process starts again from the beginning. This is necessary because the largest element has now been bubbled up to the correct position at the end of the list, but the rest of the list might still be unsorted.
  4. Fewer Comparisons Each Round: With each complete pass through the list, the next largest element settles into its correct position, just like the previous largest did. Therefore, each subsequent pass needs to do one less comparison because each pass guarantees that the elements at the end are in their correct positions.
  5. Stopping Early: If during a pass no swaps are made, the algorithm can stop early because this means the list is already sorted.

What Bubble Sort is Used For

Bubble sort is primarily used in educational settings to teach students about algorithms, due to its simplicity. It is rarely used in practical applications because it’s not very efficient compared to other sorting algorithms like quicksort or mergesort, especially for larger lists. The main drawbacks are:

  • Inefficiency: Bubble sort requires many comparisons and swaps to sort even moderately sized lists.
  • Time Consumption: It can be very slow, taking a lot of time to sort large datasets.

Despite these limitations, bubble sort can be useful in scenarios where simplicity is more valuable than efficiency, or where the datasets are typically small and nearly sorted already (because it can detect and end early when the list is sorted).

Understanding bubble sort provides a good foundation for learning more complex sorting algorithms and grasping general concepts used in computer programming and data handling.

How Does the Bubble Sort Algorithm Work in VB.NET? To implement the Bubble Sort algorithm in Visual Basic .NET, you can follow this simple example:

Visual Basic .NET BubbleSort Ver 1.0 Bernard Aybout

Copy to Clipboard

Let’s go through the VB.NET code for the BubbleSort displayed above, line by line:

Module Module1

This line declares a module named Module1. In VB.NET, a module is a container for procedures (Subs or Functions), variables, and data structures. All items within a module are globally accessible but scoped to the project.

Sub Main()

This line defines the Main subroutine, which is the entry point for the application. When the program starts, execution begins from here.

Dim arr() As Integer =

This line declares and initializes an array arr of integers with the values . This is the array that will be sorted using the Bubble Sort algorithm.

BubbleSort(arr)

This line calls the BubbleSort subroutine, passing the arr array as an argument by reference. This means any changes made to arr inside the BubbleSort subroutine will reflect on the original array in Main.

Console.WriteLine("Sorted array:")

This line prints the text “Sorted array:” to the console, serving as a label for the output that follows.

For Each element In arr

This For Each loop iterates through each element in the arr array.

Console.Write(element & " ")

Inside the loop, this line prints each element of the array followed by a space. This prints all the elements of the array on the same line.

Next

This line marks the end of the For Each loop.

Console.ReadKey()

This line waits for the user to press a key before the program terminates, preventing the console window from closing immediately after executing.

End Sub

This line marks the end of the Main subroutine.

Sub BubbleSort(ByRef arr() As Integer)

This line defines the BubbleSort subroutine with one parameter, arr, which is an array of integers passed by reference.

Dim temp As Integer

This line declares a variable temp of type Integer. This variable is used to temporarily hold values for swapping elements in the array.

For i As Integer = 0 To arr.Length - 2

This For loop iterates from 0 to the length of the array minus two. It controls the number of passes the sorting algorithm needs to make through the array.

For j As Integer = 0 To arr.Length - 2 - i

This nested For loop iterates from 0 up to the length of the array minus two minus the current pass number i. This loop compares adjacent elements and swaps them if they are in the wrong order.

If arr(j) > arr(j + 1) Then

This If statement checks if the current element is greater than the next element. If true, it means they are in the wrong order and need to be swapped.

temp = arr(j)
arr(j) = arr(j + 1)
arr(j + 1) = temp

These three lines perform the swap; temp temporarily holds the value of arr(j), then arr(j) is set to the value of arr(j + 1), and finally, arr(j + 1) is set to the value held in temp.

End If

This line marks the end of the If block.

Next

This line marks the end of the inner For loop.

Next

This line marks the end of the outer For loop.

End Sub

This line marks the end of the BubbleSort subroutine.

End Module

This line marks the end of Module1.

That’s the breakdown of the VB.NET BubbleSort program, explaining how each line contributes to its functionality.


Update – Robust Programming practise:

Our Visual Basic .NET code for performing a bubble sort and printing the sorted array above looks good overall. It correctly implements the bubble sort algorithm and should function as expected to sort the given array. However, there are a few enhancements and best practices that you could consider to improve the code:

  1. Explicitly Declare Array Size: While it’s not strictly necessary, explicitly declaring the size of the array when initializing it can make the code clearer, especially in more complex scenarios.
  2. Adding Comments: Your code already includes good comments, but adding a few more comments to explain what certain loops or if conditions are doing can make it more readable, especially for someone new to bubble sort.
  3. Optimization: While bubble sort isn’t the most efficient sorting algorithm for large datasets, you can add a simple optimization to avoid unnecessary passes once the array is sorted. You can introduce a flag to monitor whether any swaps were made in the inner loop; if no swaps were made, the array is sorted, and you can break out of the loop early.
  4. Encapsulation: Consider encapsulating the sorting logic in a class if you plan to use it extensively or expand it. This makes the code more modular and reusable.

Here’s a revised version of code incorporating these advanced, robust  suggestions:

Revised – Visual Basic .NET BubbleSort Ver 2.0 Bernard Aybout

Copy to Clipboard

This version includes a flag swapped that checks if any elements were swapped during a pass of the inner loop. If no elements were swapped, it breaks out of the outer loop early, which can significantly improve performance for nearly sorted or already sorted arrays.

Here’s a breakdown of the newly revised Visual Basic .NET code for performing a BubbleSort and printing the sorted array:

Module Module1

This line declares a module named Module1. A module in VB.NET is a container for procedures, functions, and variables. It allows code to be grouped together logically and can be accessed globally within the project.

    Sub Main()

This line declares the main subroutine Main, which is the entry point of the VB.NET application. When the program is run, this is the first block of code that gets executed.

        ' Initialize the array of integers
        Dim arr() As Integer = 

This line declares and initializes an array of integers named arr with the values . Dim is used to declare a variable in VB.NET, and the values inside the curly braces are the initial elements of the array.

        ' Perform bubble sort on the array
        BubbleSort(arr)

This calls the BubbleSort subroutine, passing the arr array as an argument by reference (ByRef). This means any changes made to arr inside the BubbleSort subroutine will reflect in the Main subroutine.

        ' Output the sorted array to the console
        Console.WriteLine("Sorted array:")

This line prints the string “Sorted array:” to the console, serving as a label for the output that follows.

        For Each element In arr

This begins a For Each loop that iterates over each element in the arr array. The variable element holds the current element of the array during each iteration of the loop.

            Console.Write(element & " ")

This line prints the current element followed by a space to the console without advancing to a new line, effectively printing all elements on the same line.

        Next

This marks the end of the For Each loop.

        Console.WriteLine() ' Adds a newline for cleaner output

This writes a new line to the console, ensuring that any subsequent console output starts on a new line.

        Console.ReadKey()

This line waits for the user to press a key before the console window closes, allowing the user to see the output before the program terminates.

    End Sub

This marks the end of the Main subroutine.

    ' Bubble sort algorithm with optimization to stop early if no swaps are needed
    Sub BubbleSort(ByRef arr() As Integer)

This declares a subroutine named BubbleSort, which takes an array of integers arr as a parameter by reference (ByRef). The subroutine is intended to sort the array using the bubble sort algorithm.

        Dim temp As Integer

This line declares a temporary integer variable temp, which is used to swap elements in the array.

        Dim swapped As Boolean

This line declares a boolean variable swapped. It’s used to track whether any swaps have been made during a pass through the array. If no swaps occur, the array is considered sorted, and the sort can terminate early.

        ' Loop through each element in the array
        For i As Integer = 0 To arr.Length - 2

This For loop iterates from 0 to the second-to-last index of the array (arr.Length - 2). i is the index of the current pass through the array from the start to the penultimate element.

            swapped = False

This line sets swapped to False at the beginning of each outer loop iteration, preparing to detect if any swaps occur in this pass.

            For j As Integer = 0 To arr.Length - 2 - i

This nested For loop iterates from 0 to arr.Length - 2 - i, reducing the range each time since the largest elements bubble to the end of the array with each outer loop pass.

                ' If the current element is greater than the next element, swap them
                If arr(j) > arr(j + 1) Then

This If statement checks if the current element is greater than the next element. If it is, they need to be swapped to sort the array.

                    temp = arr(j)
                    arr(j) = arr(j + 1)
                    arr(j + 1) = temp

These lines perform the swap: temp stores the current element, the current element gets the value of the next element, and then the next element gets the value stored in temp.

                    swapped = True

This sets swapped to True because a swap occurred.

                End If
            Next

This marks the end of the inner loop.

            ' If no elements were swapped, break out of the loop early
            If Not swapped Then
                Exit For

This checks if no swaps were made during the pass (swapped is False). If true, it breaks out of the outer loop early because the array must already be sorted.

            End If
        Next
    End Sub

This marks the end of the outer loop and the end of the BubbleSort subroutine.

End Module

This marks the end of the Module1.


Exit mobile version