How to sort a list that consists of only 0s and 1s in VB.NET

1 Answer

0 votes
Imports System
Imports System.Collections.Generic

Class Program
    Private Shared Sub SortBinaryList(ByVal arr As List(Of Integer))
        Dim left As Integer = 0 ' Index to track the left side
        Dim right As Integer = arr.Count - 1 ' Index to track the right side

        While left < right
            If arr(left) = 0 Then
                Console.WriteLine("left: " & left)
                left += 1
            ElseIf arr(right) = 1 Then
                Console.WriteLine("right: " & right)
                right -= 1
			' If left is 1 and right is 0, swap them
            Else
                Dim temp As Integer = arr(left)
                arr(left) = arr(right)
                arr(right) = temp
                Console.WriteLine("swap() left: " & left & " right: " & right)
                left += 1
                right -= 1
            End If
        End While
    End Sub

    Public Shared Sub Main()
        Dim arr As List(Of Integer) = New List(Of Integer) From {
            1,
            0,
            1,
            0,
            1,
            0,
            0,
            1,
            0
        }
		
        SortBinaryList(arr)
        Console.Write("Sorted list: ")

        For Each num As Integer In arr
            Console.Write(num & " ")
        Next
    End Sub
End Class



' run:
'
' swap() left: 0 right: 8
' left: 1
' right: 7
' swap() left: 2 right: 6
' left: 3
' swap() left: 4 right: 5
' Sorted list: 0 0 0 0 0 1 1 1 1 
'

 



answered Sep 2 by avibootz
...