Nilay Vishwakarma
Nilay Vishwakarma

Reputation: 3363

How is Icomparer.Compare() method called when Sort is implemented?

Consider the following sample.

Array.Sort(Myfiles, new customSort())
.
.
.
private class customSort : IComparer<object>
{
 public override int Compare(obj A, obj B)
 {
   return (A.Value==B.Value?(0):((A.Value < B.Value)?(-1):(1)));
 }
}

If Myfiles contain collection of objects,

Upvotes: 1

Views: 423

Answers (3)

vvv
vvv

Reputation: 398

This method uses the introspective sort (introsort) algorithm as follows:

  • If the partition size is fewer than 16 elements, it uses an insertion sort algorithm.
  • If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm.
  • Otherwise, it uses a Quicksort algorithm.

From http://msdn.microsoft.com/en-us/library/kwx6zbd4.aspx

For first option here is a nice gif: http://en.wikipedia.org/wiki/Insertion_sort#mediaviewer/File:Insertion-sort-example-300px.gif

Upvotes: 1

Dirk
Dirk

Reputation: 10958

That depends on the sort algorithm. When the algorithm has to compare two objects to determine their relative order it calls the Compare method.

For algorithms like Bubblesort A and B would be neighbors, for anything else I can think of right now they could be any objects in the collection.

Upvotes: 1

CyberDude
CyberDude

Reputation: 8949

Obviously the call occurs within the Sort method. All the other questions pertain to the internal implementation of the Sort method. Although you may peek inside the actual logic, you should not normally bother since you are only interested in the end result (i.e. your array becoming sorted).

Upvotes: 0

Related Questions