Sort Delegate : Delegate « Language Basics « VB.Net






Sort Delegate

Sort Delegate
 
Imports System

Public Class MainClass
   Shared Dim mBubbleSort As New CDelegateBubbleSort()

   Shared Dim mElementArray As Integer() = New Integer(9) {}
    
    Shared Sub Main(ByVal args As String())
      Dim randomNumber As Random = New Random()
      Dim i As Integer

      Console.WriteLine("Init Value:")
      ' create String with 10 random numbers
      For i = 0 To mElementArray.GetUpperBound(0)
         mElementArray(i) = randomNumber.Next(100)
         Console.WriteLine( mElementArray(i) )
      Next

      mBubbleSort.SortArray(mElementArray, AddressOf SortAscending)

      Console.WriteLine("Sort Ascending")

      For i = 0 To mElementArray.GetUpperBound(0)
         Console.WriteLine( mElementArray(i) )
      Next

      mBubbleSort.SortArray(mElementArray, AddressOf SortDescending)
      Console.WriteLine("Sort Descending")

      For i = 0 To mElementArray.GetUpperBound(0)
         Console.WriteLine( mElementArray(i) )
      Next

    End Sub


   ' delegate implementation sorts in asending order
   Shared Private Function SortAscending(ByVal element1 As Integer, _
      ByVal element2 As Integer) As Boolean

      Return element1 > element2
   End Function ' SortAscending

   ' delegate implementation sorts in descending order
   Shared Private Function SortDescending(ByVal element1 As Integer, _
      ByVal element2 As Integer) As Boolean

      Return element1 < element2
   End Function ' SortDescending

End Class


Public Class CDelegateBubbleSort
   Public Delegate Function Comparator( _
      ByVal element1 As Integer, _
      ByVal element2 As Integer) As Boolean

   Public Sub SortArray(ByVal array As Integer(), _
      ByVal Compare As Comparator)
      Dim i, pass As Integer
      For pass = 0 To array.GetUpperBound(0)
         For i = 0 To array.GetUpperBound(0) - 1
            If Compare(array(i), array(i + 1)) Then
               Swap(array(i), array(i + 1))
            End If
         Next
      Next
   End Sub
   Private Sub Swap(ByRef firstElement As Integer, _
      ByRef secondElement As Integer)
      Dim hold As Integer
      hold = firstElement
      firstElement = secondElement
      secondElement = hold
   End Sub ' Swap

End Class
           
         
  








Related examples in the same category

1.Delegate with and without parametersDelegate with and without parameters
2.Two ways to init a DelegateTwo ways to init a Delegate
3.Multicast DelegateMulticast Delegate
4.Use Delegate to implement custome sortUse Delegate to implement custome sort
5.Register Delegates and call themRegister Delegates and call them
6.Simple Delegate DemoSimple Delegate Demo
7.Function Delegation DemoFunction Delegation Demo
8.Function Delegate: output stringFunction Delegate: output string
9.Delegate Demo for a Simple ClassDelegate Demo for a Simple Class
10.Delegate Syntax