How can we sort points in c#? There is no one way to sort points, it all depends on which value we are looking at: X or Y. Sorting respective to the X values will sort an array of points from left to right (or vice versa). Likewise sorting the Y values sorts the points top to bottom. This is useful when applying more advanced processing algorithms to a list of points. An example is image distortion agorithms, where a list of sorted corners is crucial.
To sort the points, we are going to create a class that inherits the interface IComparer. The main meat of the function will be the Compare function which will, depending on whether to sort left to right or top to bottom, will compare the X or Y values of the points. The actual sorting algorithm is handled by the .Net Framework, all we need to do in the Compare function is establish what makes one point greater than, less than, or equal to a second point.
Here is the header of the function:
int IComparer.Compare(object a, object b)
Note that the parameter types are object, this is so the .Net Framework can easily call the function later. Accordingly the objects need to be converted to Points before we do anything. Simply use (Point)a and (Point)b.
Notice how the function Compare returns an int, the int has to be one of three values:
0 - The two objects are equal
1 - The first object is greater than the second object
-1 - The first object is less than the second object
Then calling the actual sorting is quite simple:
Array.Sort(pointArray, new PointSort(PointSort.Mode.X));
Since the actual sorting is done by the .Net Framework, the process has already been optimized to run at decent speeds. I detail I did not include is that the PointSort class needs to know by which value (X or Y) to sort by, that's what PointSort.Mode is for. To view how the whole thing comes together, download the project files.
More review : Buy Best Price Buy Best Price
ไม่มีความคิดเห็น:
แสดงความคิดเห็น