How to sort an array with a single loop in VB.NET

1 Answer

0 votes
Imports System

Module Program

    ''' <summary>
    ''' Swaps two integer values in place using pass-by-reference.
    ''' </summary>
    Private Sub Swap(ByRef a As Integer, ByRef b As Integer)
        Dim temp As Integer = a
        a = b
        b = temp
    End Sub

    ''' <summary>
    ''' Sorts an integer array in non-decreasing order using Gnome Sort.
    ''' 
    ''' Algorithm Logic (Single Loop):
    ''' - Advances through the array using a single while loop index.
    ''' - Moves forward when adjacent elements are in correct relative order.
    ''' - When an out-of-order adjacent pair is encountered, swaps the elements
    '''   and steps backward one index to verify order against preceding items.
    ''' - Time Complexity: O(N) best case (already sorted), O(N^2) worst case.
    ''' - Space Complexity: O(1) auxiliary space.
    ''' </summary>
    ''' <param name="arr">The array of integers to sort in place.</param>
    Public Sub SingleLoopSort(arr As Integer())
		Dim len AS Integer = arr.Length
        
		If arr Is Nothing OrElse len <= 1 Then
            Return
        End If

        Dim pos As Integer = 0

		While pos < len
            ' Move forward if at the start or if the current pair is sorted
            If pos = 0 OrElse arr(pos) >= arr(pos - 1) Then
                pos += 1
            Else
                ' Swap adjacent out-of-order elements and step backward
                Swap(arr(pos), arr(pos - 1))
                pos -= 1
            End If
        End While
    End Sub

    Sub Main()
        Dim numbers As Integer() = {42, -5, 12, 0, 89, -18, 33, 7}

        Console.WriteLine("Original array:")
        Console.WriteLine(String.Join(" ", numbers))

        SingleLoopSort(numbers)

        Console.WriteLine()
        Console.WriteLine("Sorted array:")
        Console.WriteLine(String.Join(" ", numbers))
    End Sub

End Module


' run:
' 
' Original array:
' 42 -5 12 0 89 -18 33 7
' 
' Sorted array:
' -18 -5 0 7 12 33 42 89
'

 



answered Aug 8 by avibootz
...