|Silverlight Sorting Lab|
|Written by Ian Elliot|
|Tuesday, 12 October 2010|
Page 3 of 6
The first sort method that is worth investigating is the terrible “bubble” sort.
This is one of the worst sorting methods you could possibly choose but it is simple and it is interesting to see why it is so awful.
There are three simple improvements that can be made to the terrible bubble sort that make it a little better and these can be investigated as options in the Sort Lab.
Add a new button and three RadioButtons. Change their captions to “Sort”, “Reducing” and “Bi-directional”.To make the RadioButtons work as a group set their GroupName to Bubble and set the Sort RadioButton IsChecked property to true:
<Button Content="Bubble Sort"
In this case we have to run the actual bubble sort methods in a non-UI thread and again the swap method in the UI thread.
Instead of using the BackgroundWorker thread class as for the shuffle let's implement the threading directly, i.e. create and start threads to do the job.
Let's look in detail at implementing just the simple basic bubble sort. The button click event handler has to call the correct Bubble sort depending on the state of the Radio buttons. As we are focusing on the basic bubble sort the reduced version of the handler is:
private void button3_Click(object sender,
Notice that all it does is to create and start a thread running the correct bubble sort method.
The bubble sort methods can now be written ignoring the fact that they are being run on a separate thread. To do the data and UI update they simply call swapData:
Notice that the one thing that the bubble sort routine has to do is to reset the Working flag to indicate that it has finished.
The key to being able to ignore the thread that the bubble sort is running on is that the swapData method has to run the UI part of the swap on the UI thread. It starts off much as before:
void swapData(int i,int j)
With the data swapped it is time to swap the UI components and to do this we need to define a delegate with the correct signature. We can't simply use an anonymous method or a lambda expression in this case because the parameter type is Delegate and this doesn't provide any information about the signature of the method being passed.
The delegate type is just:
delegate void UIswap(int i, int j);
and the actual delegate object is:
UIswap swap= ( i1, j1)=>
Now we can use the BeingInvoke dispatcher method to run the delegate on the UI thread:
Notice the way that the parameters are packaged up into an object array as part of the call. Also using the Deployment object to get the current Dispatcher is in theory the only safe way of getting the Dispatcher associated with the UI thread.
An alternative way of doing the same job which is much neater is to define a lambda expression with no parameters and use closure to provide the i,j values as in:
|Last Updated ( Tuesday, 12 October 2010 )|