|
|
Delegates
Sort.cs
using System;
delegate int Comparer(object x, object y);
class Fraction {
public int a, b;
public Fraction(int a, int b) { this.a = a; this.b = b; }
public override string ToString() { return a + "/" + b; }
}
class Test {
static int CompareFraction(object x, object y) {
Fraction f1 = (Fraction)x;
Fraction f2 = (Fraction)y;
float fract1 = (float)f1.a / f1.b;
float fract2 = (float)f2.a / f2.b;
if (fract1 < fract2) return -1;
else if (fract1 > fract2) return 1;
else return 0;
}
static int CompareString(object x, object y) {
return ((string)x).CompareTo(y);
}
static void Sort(object[] a, Comparer compare) {
// selection sort
for (int i = 0; i < a.Length-1; i++) {
int min = i;
for (int j = i+1; j < a.Length; j++) {
if (compare(a[j], a[min]) < 0) min = j;
}
if (min != i) { object x = a[i]; a[i] = a[min]; a[min] = x; }
}
}
public static void Main() {
Fraction[] a = { new Fraction(1,2), new Fraction(3,4), new Fraction(4,8), new Fraction(8,3)};
string[] b = {"pears", "apples", "oranges", "bananas", "plums"};
Sort(a, new Comparer(CompareFraction));
foreach (Fraction f in a) Console.Write(f + " ");
Console.WriteLine();
Sort(b, new Comparer(CompareString));
foreach (string s in b) Console.Write(s + " ");
Console.WriteLine();
}
}
|
|