How to sort array into zig zag pattern (a < b > c < d > e < f > g) in VB.NET

2 Answers

0 votes
Imports System

Public Class Program
    Public Shared Sub SortArrayIntoZigZagPattern(ByVal arr As Integer())
        Dim small As Boolean = True
        Dim size As Integer = arr.Length

        For i As Integer = 0 To size - 2
            If small Then
                If arr(i) > arr(i + 1) Then
                    Dim temp As Integer = arr(i)
                    arr(i) = arr(i + 1)
                    arr(i + 1) = temp
                End If
            Else

                If arr(i) < arr(i + 1) Then
                    Dim temp As Integer = arr(i)
                    arr(i) = arr(i + 1)
                    arr(i + 1) = temp
                End If
            End If

            small = Not small
        Next
    End Sub

    Public Shared Sub Main(ByVal args As String())
        Dim arr As Integer() = New Integer() {3, 5, 1, 7, 9, 6, 4, 2}
        
		SortArrayIntoZigZagPattern(arr)
        
		Console.WriteLine(String.Join(" ", arr))
    End Sub
End Class



' run:
'
' 3 5 1 9 6 7 2 4
'

 



answered Nov 6, 2022 by avibootz
0 votes
Imports System

Public Class Program
    Private Shared Sub Swap(Of T)(ByRef a As T, ByRef b As T)
        Dim temp As T = a
        a = b
        b = temp
    End Sub

    Private Shared Sub SortArrayIntoZigZagPattern(ByVal arr As Integer())
        Dim small As Boolean = True
        Dim size As Integer = arr.Length

        For i As Integer = 0 To size - 2
            If small Then
                If arr(i) > arr(i + 1) Then
                    Swap(arr(i), arr(i + 1))
                End If
            Else
                If arr(i) < arr(i + 1) Then
                    Swap(arr(i), arr(i + 1))
                End If
            End If

            small = Not small
        Next
    End Sub

    Public Shared Sub Main(ByVal args As String())
        Dim arr As Integer() = New Integer() {3, 5, 1, 7, 9, 6, 4, 2}

        SortArrayIntoZigZagPattern(arr)

        Console.WriteLine(String.Join(" ", arr))
    End Sub
End Class




' run:
'
' 3 5 1 9 6 7 2 4
'

 



answered Nov 6, 2022 by avibootz
edited Nov 6, 2022 by avibootz
...