|
|
Sorting vectors
Chap4_Ex2.cs
using System;
using System.Collections;
public class Vector : IComparable {
private double x, y;
public Vector(double x, double y) {
this.x = x; this.y = y;
}
public double Length {
get {
return Math.Sqrt(x*x + y*y);
}
}
public int CompareTo(object obj) {
Vector v = obj as Vector;
if(v == null) throw new ArgumentException();
return this.Length - v.Length;
}
public override String ToString() { return "vector ("+x+", "+y+") length="+this.Length; }
}
public class Cap4_Ex2_Test {
public static void Main(string[] argv) {
Vector[] vArray = {new Vector(1.5,2.3), new Vector(3,6), new Vector(2,2)};
Array.Sort(vArray);
dumpArray(vArray);
Array.Reverse(vArray);
dumpArray(vArray);
}
public static void dumpArray(Array a) {
foreach(object o in a) Console.WriteLine(o);
}
}
|
|