This program is altered for simplicity. For example data given to ID 100, 200 and 300. Return will be 1, -1 or 0. this.ID can take 100, 200 or 300. What value tem.ID can take. Problem is highlighted.
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 { get; set; }
public int CompareTo(object student)
{
Student tem = (Student)student; //Note: 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
*/
Loading
VulpesPosted Feb 27, 2012, 7:01 AM
The output on my machine was:
So the answer to your question is that when this.ID is 100, tem.ID is 200.
Posted Feb 27, 2012, 11:39 AM
VulpesPosted Feb 27, 2012, 10:58 AM
http://en.wikipedia.org/wiki/Quicksort
This is very efficient for sorting large arrays but inefficient for sorting small arrays (up to about 9 elements)
You can certainly see that here as it's taking 5 comparisons to sort only 3 elements and one of them is repeated.
If you change the program to accept 4 numbers and input 400, 300, 200, 100 then you'll find that 12 comparisons are needed and that there are a lot of repetitions amongst them:
this.ID is 400, tem.ID is 300
this.ID is 300, tem.ID is 100
this.ID is 400, tem.ID is 300
this.ID is 100, tem.ID is 300
this.ID is 300, tem.ID is 400
this.ID is 300, tem.ID is 200
this.ID is 100, tem.ID is 200
this.ID is 100, tem.ID is 200
this.ID is 100, tem.ID is 200
this.ID is 300, tem.ID is 400
this.ID is 300, tem.ID is 400
this.ID is 300, tem.ID is 400
In practice, this inefficiency doesn't really matter as sorting small arrays is fast on today's machines, whatever method is used.
Posted Feb 27, 2012, 7:39 AM
this.ID is 300, tem.ID is 200
this.ID is 200, tem.ID is 100
this.ID is 300, tem.ID is 200
this.ID is 100, tem.ID is 200
this.ID is 200, tem.ID is 300
Posted Feb 27, 2012, 7:18 AM
If I have problem I will get back to you.
Posted Feb 27, 2012, 6:44 AM
VulpesPosted Feb 27, 2012, 4:59 AM
The reason is that the Array.Sort routine will call the CompareTo method using successive elements in the array until eventually those elements are in sorted order.