How to rearrange an array such that every second element becomes greater than its left and right element with VB.NET

1 Answer

0 votes
Imports System

Public Class Program
    Public Shared Sub swap(ByVal arr As Integer(), ByVal i As Integer, ByVal j As Integer)
        Dim temp As Integer = arr(i)
        arr(i) = arr(j)
        arr(j) = temp
    End Sub

    Public Shared Sub rearrangeArray(ByVal arr As Integer())
        Dim size As Integer = arr.Length

        For i As Integer = 1 To size - 1 Step 2

            If arr(i - 1) > arr(i) Then
                swap(arr, i - 1, i)
            End If

            If i + 1 < size AndAlso arr(i + 1) > arr(i) Then
                swap(arr, i + 1, i)
            End If
        Next
    End Sub

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



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

 



answered Sep 30, 2023 by avibootz
...