using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
// WeirdInteger defines a custom sort order where
// negative numbers are bigger than positive ones.
WeirdInteger[] ary = new WeirdInteger[7];
ary[0] = new WeirdInteger(-1);
ary[1] = new WeirdInteger(1);
ary[2] = new WeirdInteger(2);
ary[3] = new WeirdInteger(-2);
ary[4] = new WeirdInteger(-3);
ary[5] = new WeirdInteger(3);
ary[6] = new WeirdInteger(0);
// Array.Sort is calling the CompareTo method in WeirdInteger
// repeatedly - control has been inverted here.
Array.Sort(ary);
// Expected order is 0,1,2,3 (ascending integers but
// 'less than' the negative integers) and then -3,-2,-1
// (ascending negative integers)
foreach (WeirdInteger i in ary)
Console.WriteLine(i.ToString());
Console.ReadLine();
}
}
class WeirdInteger : IComparable
{
private int value;
internal WeirdInteger(int value)
{ this.value = value; }
#region IComparable Members
// Sort our integers such that any value less than
// zero is bigger than a value greater than zero. Otherwise
// sort normally. This means that -1 is the largest possible number.
public int CompareTo(object obj)
{
int otherValue = ((WeirdInteger)obj).value;
if (value == otherValue)
return 0;
else if (value < 0 && otherValue >= 0)
return 1;
else if (otherValue < 0 && value >= 0)
return -1;
else
return value.CompareTo(otherValue);
}
#endregion
public override string ToString()
{
return value.ToString();
}
}
}
Like this:
Like Loading...
Thanks a lot Rich.Gives me a lot of clarity.
Thank Rich. The way you are explaining making easy to the developers to digest the concept.