VB .NET Program to Implement Shell Sort

VB .NET Program to Implement Shell Sort

Sorting is one of the most common tasks in programming. Whether you are organizing numbers, names, or scores, having them in order makes it easier to search, analyze, or display data. Shell Sort is a powerful sorting algorithm that improves on the basic insertion sort by allowing the exchange of far apart elements. This can make sorting much faster for larger datasets, which is why it is often taught to beginners as a step toward understanding more advanced sorting techniques.

Pluralsight Logo
Accelerate your tech career
with hands-on learning.
Whether you're a tech newbie or a total pro,
get the skills and confidence to land your next move.
Start 10-Day Free Trial

Shell Sort works by comparing elements that are a certain “gap” distance apart and gradually reducing this gap until it becomes 1, at which point it performs a final insertion sort. It is especially useful for arrays where elements are initially far from their correct position, as it reduces the total number of swaps needed. In practical applications, Shell Sort can be used for ranking lists, sorting grades, or arranging records in small to medium-sized datasets.

Program 1: Basic Shell Sort Using Loops

This program demonstrates the classic Shell Sort using simple nested loops. It is suitable for beginners to understand the gap-based sorting mechanism.

Module Module1

    Sub ShellSort(arr() As Integer)

        Dim n As Integer = arr.Length
        Dim gap As Integer = n \ 2

        While gap > 0

            For i As Integer = gap To n - 1

                Dim temp As Integer = arr(i)
                Dim j As Integer = i

                While j >= gap AndAlso arr(j - gap) > temp
                    arr(j) = arr(j - gap)
                    j -= gap
                End While

                arr(j) = temp

            Next

            gap \= 2

        End While

    End Sub

    Sub Main()

        Dim data() As Integer = {12, 34, 54, 2, 3}
        ShellSort(data)

        For Each num In data
            Console.Write(num & " ")
        Next

        Console.ReadLine()

    End Sub

End Module

This version works by reducing the gap size gradually and performing insertion sort for each gap. Beginners can see how elements move closer to their correct positions step by step.

Program 2: Shell Sort With Predefined Gap Sequence

This example shows how using a predefined sequence of gaps can improve efficiency, instead of just halving the gap each time.

Module Module1

    Sub ShellSort(arr() As Integer)

        Dim gaps() As Integer = {5, 3, 1} ' Custom gap sequence

        For Each gap In gaps

            For i As Integer = gap To arr.Length - 1

                Dim temp As Integer = arr(i)
                Dim j As Integer = i

                While j >= gap AndAlso arr(j - gap) > temp
                    arr(j) = arr(j - gap)
                    j -= gap
                End While

                arr(j) = temp

            Next

        Next

    End Sub

    Sub Main()

        Dim data() As Integer = {23, 12, 1, 8, 34, 54, 2}
        ShellSort(data)

        For Each num In data
            Console.Write(num & " ")
        Next

        Console.ReadLine()

    End Sub

End Module

Using a custom gap sequence can improve performance in certain scenarios, making this approach useful for more advanced applications while still being easy for beginners to follow.

Program 3: Shell Sort With Negative Numbers

This version demonstrates that Shell Sort works with arrays containing negative numbers as well.

Module Module1

    Sub ShellSort(arr() As Integer)

        Dim n As Integer = arr.Length
        Dim gap As Integer = n \ 2

        While gap > 0

            For i As Integer = gap To n - 1

                Dim temp As Integer = arr(i)
                Dim j As Integer = i

                While j >= gap AndAlso arr(j - gap) > temp
                    arr(j) = arr(j - gap)
                    j -= gap
                End While

                arr(j) = temp

            Next

            gap \= 2

        End While
    End Sub

    Sub Main()

        Dim data() As Integer = {12, -5, 34, -2, 0, 3}
        ShellSort(data)

        For Each num In data
            Console.Write(num & " ")
        Next

        Console.ReadLine()

    End Sub

End Module

This example shows that Shell Sort does not require any special adjustments for negative numbers and handles them naturally during comparisons.

Program 4: Shell Sort With User Input

This program allows the user to input numbers, making it more interactive.

Module Module1

    Sub ShellSort(arr() As Integer)

        Dim n As Integer = arr.Length
        Dim gap As Integer = n \ 2

        While gap > 0

            For i As Integer = gap To n - 1

                Dim temp As Integer = arr(i)
                Dim j As Integer = i

                While j >= gap AndAlso arr(j - gap) > temp
                    arr(j) = arr(j - gap)
                    j -= gap
                End While

                arr(j) = temp

            Next

            gap \= 2

        End While

    End Sub

    Sub Main()

        Console.WriteLine("Enter numbers separated by space:")

        Dim input As String = Console.ReadLine()
        Dim data() As Integer = Array.ConvertAll(input.Split(" "c), AddressOf Integer.Parse)

        ShellSort(data)

        Console.WriteLine("Sorted array:")

        For Each num In data
            Console.Write(num & " ")
        Next

        Console.ReadLine()

    End Sub

End Module

This version is perfect for beginners who want to experiment with different numbers dynamically.

Program 5: Shell Sort Using Functions

Here, the sorting logic is separated into a function for better readability and reusability.

Module Module1

    Function ShellSort(arr() As Integer) As Integer()

        Dim n As Integer = arr.Length
        Dim gap As Integer = n \ 2

        While gap > 0

            For i As Integer = gap To n - 1

                Dim temp As Integer = arr(i)
                Dim j As Integer = i

                While j >= gap AndAlso arr(j - gap) > temp
                    arr(j) = arr(j - gap)
                    j -= gap
                End While

                arr(j) = temp

            Next

            gap \= 2

        End While

        Return arr

    End Function

    Sub Main()

        Dim data() As Integer = {9, 8, 3, 7, 5, 6, 4, 1}
        data = ShellSort(data)

        For Each num In data
            Console.Write(num & " ")
        Next

        Console.ReadLine()

    End Sub

End Module

This makes the code modular, showing beginners how to organize larger programs and reuse logic efficiently.

Frequently Asked Questions (FAQ)

Shell Sort is a common topic for beginners, so here are some questions you may have:

Q1: Is Shell Sort faster than Insertion Sort?
Yes, for large arrays, Shell Sort can be much faster because it moves elements long distances in early iterations, reducing the total number of comparisons and swaps.

Q2: Can Shell Sort handle negative numbers?
Absolutely. Shell Sort only compares values, so negative numbers are naturally handled.

Q3: What is the time complexity of Shell Sort?
The time complexity depends on the gap sequence. In general, it ranges from O(n^2) in worst case to O(n log^2 n) for optimized gap sequences.

Q4: Is Shell Sort a stable sort?
No, Shell Sort is not stable because it can change the relative order of equal elements during swaps.

Q5: Can I use Shell Sort for strings?
Yes, you can sort strings by comparing them lexicographically instead of numerically.

Conclusion

Shell Sort is a powerful and versatile sorting algorithm that sits nicely between simple insertion sort and more advanced algorithms like Quick Sort. Its gap-based approach allows for faster sorting on larger arrays while still being simple enough for beginners to understand. By experimenting with different gap sequences, negative numbers, and user input, you can gain a solid understanding of sorting mechanics. Practicing these programs in VB .NET will give you confidence in handling arrays and developing more complex algorithms in the future.

Scroll to Top