Passing Delegates as Arguments
The classic example of procedural types is to pass the address of functions to sorting algorithms. As in the "Hello World!" examples, it's almost tradition to demonstrate procedural types using sort algorithms. In this section I will demonstrate three sort algorithms that use one of two comparison functions to alternate between ascending and descending sort order.
To demonstrate passing Delegate arguments, I will guide you through the construction of SortAlgorithms.sln (contained on this book's companion web site, and shown in Figure 2). To complete the sample program, we will define a Compare Delegate that compares two integers. To perform comparisons based on a user preference of ascending or descending order, we will define two compare procedures suitably named Greater and Less. Listing 7 shows just the Delegate definition and two function definitions. Listing 8 contains the complete SortAlgorithms.sln listing (except for the Windows Form Designergenerated code).
Figure 2 The SortAlgorithms application showing BubbleSort swaps in progress.
Listing 7The Delegate Definition and Two Suitable Functions for Instances of the Compare Delegate
1: Delegate Function Compare(ByVal Height1 As Integer, _ 2: ByVal Height2 As Integer) As Boolean 3: 4: Public Function Greater(ByVal H1 As Integer, _ 5: ByVal H2 As Integer) As Boolean 6: Return H1 > H2 7: End Function 8: 9: Public Function Less(ByVal H1 As Integer, _ 10: ByVal H2 As Integer) As Boolean 11: Return H1 < H2 12: End Function
Notice that the Delegate procedural value is defined as a function that takes two integers and returns a Boolean. The signatures of Greater and Less precisely match the definition of the Delegate. To declare and initialize an instance of the Compare Delegate, do so in a Dim statement such as this:
Dim LessCompare As Compare = AddressOf Less
Referring to Figure 2, the sort order is indicated by the state of the Ascending checkbox shown in the lower-right corner of the main form in Figure 2. If the box is checked, the address of the Less function will be passed to the algorithm; otherwise, the address of the Greater function will be passed to the sort algorithm.
Reviewing the Sort Algorithms and Demo Application Behavior
The basics of sorting algorithms are the mechanisms for iterating, comparing, and swapping the elements of a group of similar data. For the sample program, I added a slight twist: We will iterate, sort, and swap rectangles drawn on a form to allow the user to see the effect of a particular algorithm (and for fun).
The SortAlgorithms application initializes a System.Array of Rectangles with random heights along the top of the form containing the code. The Random generator is invoked on Form_Load (refer to Listing 7) and can be regenerated with the Sort, Randomize menu in the sample program.
Based on the sort selected from the Sort menuBubble, Selection, or Quicka specific sort is run. The iteration algorithms for the sorts are based on classic implementations of these algorithms.
The Compare algorithms compare heights of the rectangles only and swap the actual rectangles and rectangle heights because all other coordinates of the rectangles are relative to the top-left corner of the form. See Listing 8 for the complete implementation.
Sort Algorithms
The three sort algorithms were chosen because they are quite common. The Bubble sort uses a nested For loop, comparing and swapping each element where the ith element is less than or greater than the ith + n element, depending on the order of the sort. A Bubble sort performs n2 comparisons and possibly the same number of swaps (refer to BubbleSort in Listing 8).
The Selection sort is essentially a Bubble sort. Slightly better performance characteristics are achieved because the Selection sort only performs n-swaps (refer to SelectionSort in Listing 8).
The Quick sort has Log2n, or logarithmic, performance characteristics. Performance decay of a Quick sort occurs very slowly, making the Quick sort a good general-purpose, fast sort. Quick sort performance decays in highly ordered sets, with results on ordered sets decaying to those of a Selection sort (refer to QuickSort in Listing 8).
Walking Through the SortAlgorithms Demo Application
We have covered the basic steps in defining the SortAlgorithms application. Listing 8 contains the complete listing of the demo application. A synopsis follows the listing, elaborating on some of the other examples of using delegates contained in the actual solution.
Listing 8The SortAlgorithms Demo Application Uses Procedural Type Arguments with Rectangles and Sorting Algorithms for Context
1: Public Class Form1 2: Inherits System.Windows.Forms.Form 3: 4: [ Windows Form Designer generated code ] 5: 6: Private Rectangles(300) As Rectangle 7: Private FSortOrder As Boolean 8: Private CompareProcs() As Compare = _ 9: {AddressOf Less, AddressOf Greater} 10: 11: Delegate Function Compare(ByVal Height1 As Integer, _ 12: ByVal Height2 As Integer) As Boolean 13: 14: Private Function GetCompareProc(ByVal Value _ 15: As Boolean) As Compare 16: Return CompareProcs(Math.Abs(CInt(Value))) 17: End Function 18: 19: Private Sub DrawRandomBars() 20: 21: Array.Clear(Rectangles, 0, _ 22: Rectangles.GetUpperBound(0)) 23: 24: Dim I As Integer 25: 26: For I = Rectangles.GetLowerBound(0) To _ 27: Rectangles.GetUpperBound(0) 28: Rectangles(I) = New Rectangle(I * 2, 0, 1, Rnd() * 200) 29: Next 30: 31: Invalidate() 32: End Sub 33: 34: Private Sub ConditionalInvalidate() 35: If (Not CheckBoxShowSwaps.Checked) Then _ 36: Invalidate() 37: End Sub 38: 39: Private Sub DrawRectangle(ByVal Rect As Rectangle, _ 40: ByVal APen As Pen) 41: CreateGraphics.DrawRectangle(APen, Rect) 42: End Sub 43: 44: Private Sub Form1_Paint(ByVal sender As System.Object, _ 45: ByVal e As System.Windows.Forms.PaintEventArgs) _ 46: Handles MyBase.Paint 47: 48: Dim Graphics As System.Drawing.Graphics = CreateGraphics() 49: Graphics.DrawRectangles(Pens.Green, Rectangles) 50: 51: End Sub 52: 53: Public Function Greater(ByVal H1 As Integer, _ 54: ByVal H2 As Integer) As Boolean 55: 56: Return H1 > H2 57: 58: End Function 59: 60: Public Function Less(ByVal H1 As Integer, _ 61: ByVal H2 As Integer) As Boolean 62: 63: Return H1 < H2 64: 65: End Function 66: 67: Public Sub EraseOld(ByVal Rects() As Rectangle, _ 68: ByVal I As Integer, ByVal J As Integer) 69: 70: If (Not CheckBoxShowSwaps.Checked) Then Exit Sub 71: DrawRectangle(Rects(I), Pens.LightGray) 72: DrawRectangle(Rects(J), Pens.LightGray) 73: 74: End Sub 75: 76: Public Sub DrawNew(ByVal Rects() As Rectangle, _ 77: ByVal I As Integer, ByVal J As Integer) 78: 79: If (Not CheckBoxShowSwaps.Checked) Then Exit Sub 80: DrawRectangle(Rects(I), Pens.Green) 81: DrawRectangle(Rects(J), Pens.Green) 82: 83: End Sub 84: 85: Public Sub Swap(ByVal Rects() As Rectangle, _ 86: ByVal I As Integer, ByVal J As Integer) 87: 88: EraseOld(Rects, I, J) 89: 90: Dim R As Rectangle 91: R = Rects(I) 92: Rects(I) = Rects(J) 93: Rects(J) = R 94: 95: Dim X As Integer = Rects(I).X 96: Rects(I).X = Rects(J).X 97: Rects(J).X = X 98: 99: DrawNew(Rects, I, J) 100: End Sub 101: 102: Public Sub BubbleSort(ByVal Rects() As Rectangle, _ 103: ByVal CompareProc As Compare) 104: 105: Dim I, J As Integer 106: For I = 0 To Rects.GetUpperBound(0) - 1 107: 108: For J = I + 1 To Rects.GetUpperBound(0) 109: Application.DoEvents() 110: 111: If (CompareProc(Rects(I).Height, _ 112: Rects(J).Height)) Then 113: 114: Swap(Rects, I, J) 115: 116: End If 117: Next 118: Next 119: 120: End Sub 121: 122: Public Sub SelectionSort(ByVal Rects() As Rectangle, _ 123: ByVal CompareProc As Compare) 124: 125: Dim I, J, SwapIndex As Integer 126: 127: For I = 0 To Rects.GetUpperBound(0) - 1 128: SwapIndex = I 129: 130: For J = I + 1 To Rects.GetUpperBound(0) 131: If (CompareProc(Rects(SwapIndex).Height, _ 132: Rects(J).Height)) Then 133: 134: SwapIndex = J 135: 136: End If 137: Next 138: 139: Swap(Rects, I, SwapIndex) 140: Next 141: 142: End Sub 143: 144: Public Sub QuickSort(ByVal Rects() As Rectangle, _ 145: ByVal Left As Integer, ByVal Right As Integer, _ 146: ByVal Comp1 As Compare, ByVal Comp2 As Compare) 147: 148: Dim I, J As Integer 149: Dim Rect As Rectangle 150: 151: If (Right > Left) Then 152: Rect = Rects(Right) 153: I = Left - 1 154: J = Right 155: 156: Do While (True) 157: Do 158: I += 1 159: Loop While (Comp1(Rects(I).Height, Rect.Height)) 160: 161: Do 162: J = J - 1 163: If (J < Rects.GetLowerBound(0)) Then Exit Do 164: Loop While (Comp2(Rects(J).Height, Rect.Height)) 165: 166: If (I >= J) Then Exit Do 167: 168: Swap(Rects, I, J) 169: Loop 170: 171: Swap(Rects, I, Right) 172: QuickSort(Rects, Left, I - 1, Comp1, Comp2) 173: QuickSort(Rects, I + 1, Right, Comp1, Comp2) 174: 175: 176: End If 177: 178: End Sub 179: 180: Private Sub Form1_Load(ByVal sender As System.Object, _ 181: ByVal e As System.EventArgs) Handles MyBase.Load 182: 183: DrawRandomBars() 184: 185: End Sub 186: 187: Private Sub MenuExit_Click(ByVal sender As System.Object, _ 188: ByVal e As System.EventArgs) Handles MenuExit.Click 189: 190: End 191: 192: End Sub 193: 194: Private Sub MenuRandomize_Click(ByVal sender As System.Object, _ 195: ByVal e As System.EventArgs) Handles MenuRandomize.Click 196: 197: DrawRandomBars() 198: 199: End Sub 200: 201: Private Sub MenuSelection_Click(ByVal sender As System.Object, _ 202: ByVal e As System.EventArgs) Handles MenuSelection.Click 203: 204: SelectionSort(Rectangles, _ 205: GetCompareProc(CheckBoxAscending.Checked)) 206: 207: ConditionalInvalidate() 208: End Sub 209: 210: Private Sub MenuBubble_Click(ByVal sender As System.Object, _ 211: ByVal e As System.EventArgs) Handles MenuBubble.Click 212: 213: BubbleSort(Rectangles, _ 214: GetCompareProc(CheckBoxAscending.Checked)) 215: 216: ConditionalInvalidate() 217: End Sub 218: 219: Private Sub menuQuick_Click(ByVal sender As System.Object, _ 220: ByVal e As System.EventArgs) Handles menuQuick.Click 221: 222: QuickSort(Rectangles, Rectangles.GetLowerBound(0), _ 223: Rectangles.GetUpperBound(0), _ 224: GetCompareProc(Not CheckBoxAscending.Checked), _ 225: GetCompareProc(CheckBoxAscending.Checked)) 226: 227: ConditionalInvalidate() 228: End Sub 229: 230: End Class
NOTE
All of the source code for this book is contained on the accompanying companion web site. For that reason, in general, long listings will be avoided. However, Listing 8 demonstrates several programming techniques in context, so it was listed in its entirety to facilitate discussion.
The three sort subroutinesBubbleSort, SelectionSort, and QuickSortare defined on lines 102 to 178. From the listing, it's apparent that both the Bubble and Selection sorts use a nested For loop. The biggest difference is the point at which swaps are made. The Bubble sort swaps in the inner For loop, and the Selection sort swaps at the end of the outer loop. Important to our discussion is the use of the Delegate Compare as the last argument to each subroutine. This argument is satisfied by passing either AddressOf Greater or AddressOf Less to the CompareProc parameter.
The SortAlgorithms demo passes the sort ordered based on the state of the CheckBoxAscending.Checked property. In the MenuBubble_Click handler, such code might be written as follows:
If( CheckBoxAscending.Checked ) Then BubbleSort( Rectangles, AddressOf Greater ) Else BubbleSort( Rectangles, AddressOf Less ) End If
To yield a more concise implementation, as opposed to repeating the If conditional code, an array of procedural types was used. The resultant event handler was implemented as follows:
BubbleSort( Rectangles, GetCompareProc( CheckBoxAscending.Checked ))
GetCompareProc is defined as a function that uses a Boolean to index an array of the initialized Delegates. The initialized array of Delegates is defined on lines 8 and 9:
Private CompareProcs() As Compare = _{AddressOf Less, AddressOf Greater}
TIP
Sometimes using arrays of objects, like the Delegate array on lines 8 and 9 of Listing 7, can be a bit esoteric. The use of the wrapper function GetCompareProc may help clear up confusion and provides a convenient place for a block comment, letting less experienced developers in on the secret.
The array CompareProcs is an array of the Delegate Compare initialized to the AddressOf the Less and Greater functions. (Using an array instead of If conditional code generally leads to more concise machine instructions, but this wasn't verified with respect to Visual Basic .NET.) The array of Delegates does demonstrate that it is possible to have an array of complex types, including Delegates. Such an array is a more concise, reasonable alternative to using long If conditional statements or case statements.
The Quick sort lines 144 to 178takes two comparisons; it chunks the subset of elements roughly in half recursively, ordering successively smaller subsets of elements. The two delegates are used to switch the order of the sort. Based on the state of the CheckBoxAscending.Checked property, the Compare procedures are flip-flopped in the order in which they are passed. Line 159 uses the argument Comp1 and line 164 uses Comp2. Less is passed to Comp1 if the checkbox is checked and Greater to Comp2. The argument values are switched if the checkbox is unchecked. This swapping of delegates is demonstrated on lines 224 and 225.
Illustrating an Alternative to Procedural Types
The EraseOld subroutine erases an existing rectangle by drawing a masking rectangle over the existing rectangle. The DrawNew subroutine draws the rectangle in its new position. The EraseOld and DrawNew subroutines demonstrate an alternative to procedural arguments. EraseOld and DrawNew are always called in the Swap algorithm; however, the code in them is only run based on the state. Because the state of the CheckBoxShowSwaps.Checked property is checked potentially thousands of times each time Swap is called, EraseOld and DrawNew add to a sort algorithm's decay based on the number of swaps. The two methods demonstrate how conditional behavior has always been handled in the absence of procedural types: Check the conditional value each time.
Delegates used to implement dynamic behavior allow you to write code that evaluates a condition one time and then act on that state condition until the state condition changes. Using the delegates, your code only has to evaluate the desired sort order one time, prior to calling a sort algorithm. Use the conditional code without the delegates and, as is the case with the Bubble sort, your code will evaluate the state condition possibly millions of times. In a production system, a couple of million extra conditional checks will make a big difference.