In this program how to determine which should be plus sign and which should be minus sign (this.ID and tem.ID). If you have changed the sing, output is same as input. Code is highlighted in the program. For example:-
return (-this.ID + tem.ID); // Note: this.ID has minus sign and tem.ID has plus sign
input
Student #1 ID = 300
Student #2 ID = 200
Student #3 ID = 100
output
Student #1 ID = 300
Student #2 ID = 200
Student #3 ID = 100
using System;
namespace ConsoleApplication1
{
class StudetCompare
{
static void Main(string[] args)
{
int x;
Student[] student = new Student[3];
for (x = 0; x < student.Length; ++x)
{
student[x] = new Student();
Console.Write("Student #{0} ID = ", x + 1);
student[x].ID = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine();
Array.Sort(student);
for (x = 0; x < student.Length; ++x)
{
Console.WriteLine("Student #{0} ID = {1}", x + 1, student[x].ID);
}
Console.ReadKey();
}
}
class Student : IComparable
{
public int ID;
public int CompareTo(object student)
{
Student tem = (Student)student; //IComparable is non generic therefore casting
return (this.ID - tem.ID);
}
}
}
/*
Student #1 ID = 300
Student #2 ID = 200
Student #3 ID = 100
Student #1 ID = 100
Student #2 ID = 200
Student #3 ID = 300
*/