Exercises in this lecture  previous -- Keyboard shortcut: 'p'  next -- Keyboard shortcut: 'n'  Go to the slide, where this exercise belongs -- Keyboard shortcut: 'u'  

Exercise 6.3
Finding and sorting elements in an array


In this exercise we will work with searching and sorting in arrays. To be concrete, we work on an array of type Point, where Point is the type we have been programming in earlier exercises.

Via this exercise you are supposed to learn how to pass a delegate to a method such as Find and Sort. The purpose of passing a delegate to Find is to specify which point we are looking for.

Make an array of Point objects. You can, for instance, use this version of class Point. You can also use a version that you wrote as solution to one of the previous exercises.

Use the static method System.Array.Find to locate the first point in the array that satisfies the condition:

The sum of the x and y coordinates is (very close to) zero

The solution involves the programming of an appropriate delegate in C#. The delegate must be a Point predicate: a method that takes a Point as parameter and returns a boolean value.

Next, in this exercise, sort the list of points by use of one of the static Sort methods in System.Array. Take a look at the Sort methods in System.Array. There is an overwhelming amount of these! We will use the one that takes a Comparison delegate, Comparison<T>, as the second parameter. Please find this method in your documentation browser. Why do we need to pass a Comparison predicate to the Sort method?

Comparison<Point> is a delegate that compares two points, say p1 and p2. Pass an actual delegate parameter to Sort in which

   p1 <= p2 if and only if p1.X + p1.Y <= p2.X + p2.Y

Please notice that a comparsion between p1 and p2 must return an integer. A negative integer means that p1 is less than p2. Zero means that p1 is equal to p2. A positive integer means that p1 is greater than p2.

Test run you program. Is your Point array sorted in the way you excepts?


Solution