Move all negative elements to end in vb.net

Vb program for Move all negative elements to end. Here mentioned other language solution.

' Include namespace system
Imports System 
'  Vb.net program for
'  Move all negative elements at the end of array
public Class MyArray
    '  Display list elements
    Public Sub display(ByVal arr As Integer(), 
      	ByVal n As Integer)
        Dim i As Integer = 0
        While i < n
            Console.Write("  {0}", arr(i))
        i += 1
        End While
        Console.WriteLine()
    End Sub
    '  Swap the given list elements
    Public Sub swap(ByVal arr As Integer(), 
      ByVal start As Integer, ByVal [end] As Integer)
        Dim temp As Integer = arr(start)
        arr(start) = arr([end])
        arr([end]) = temp
    End Sub
    '  Method which is move negative elements
    Public Sub moveNegative(ByVal arr As Integer(),
      						ByVal n As Integer)
        '  first index
        Dim i As Integer = 0
        '  last index
        Dim j As Integer = n - 1
        while (i < j)
            if (arr(i) < 0 AndAlso arr(j) >= 0) Then
                '  When [i] index are have negative value 
                '  And [j] is positive then swapping elements values
                Me.swap(arr, i, j)
                '  Modified index
                i += 1
                j -= 1
            ElseIf (arr(i) >= 0) Then
                '  When element of [i] is not negative
                i += 1
            Else
                j -= 1
            End IF
        End While
    End Sub
    Public Shared Sub Main(ByVal args As String())
        Dim task As MyArray = New MyArray()
        '  Array which are containing positive and negative values
        Dim arr As Integer() =
        {1, -1, 3, 2, -7, -5, 11, 6}
        Dim n As Integer = arr.Length
        Console.WriteLine("Before Arrange : ")
        '  Before move element
        task.display(arr, n)
        '  Move negative elements
        task.moveNegative(arr, n)
        '  After arrange
        Console.WriteLine("After Arrange : ")
        '  After move element
        task.display(arr, n)
    End Sub
End Class

Output

Before Arrange :
  1  -1  3  2  -7  -5  11  6
After Arrange :
  1  6  3  2  11  -5  -7  -1



Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2022, kalkicode.com, All rights reserved