CODEGATOR

.NET info worth sinking your teeth into!
Welcome to CODEGATOR Sign in | Join | Help
in Search

Martin Cook

Yet another C# developer with a blog.

Random Sorting in C#

Here is another bit of code from the old CodeGator website.

I wrote a small application in 2002 that had to produce a list of Internet addresses in random order. (No, I wasn't spamming anyone!) I fumbled around with various ways of creating that list until I finally created the CGRandomSorter class. Since that time I have always had an easy way to "scramble" the contents of almost any list.

The class implements IComparer, so using it is as simple as creating an instance and passing a reference into the collection's sort method. Here is a quick example:

ArrayList list = new ArrayList();
for (int x = 0; x < 100; x++)
    list.Add(x);
CGRandomSorter sorter = new CGRandomSorter();
list.Sort(sorter);
// The list is now sorted.

 

The actual source for the CGRandomSorter class is shown here:

public sealed class CGRandomSorter : IComparer
{

    private Random m_rnd;

    public CGRandomSorter()
    {
        m_rnd = new Random((int)DateTime.Now.Ticks);
    } // End CGRandomSorter()

    int IComparer.Compare(object objA, object objB)
    {

        // The .NET framework goes wobbly if we don't
        //   return zero for x.CompareTo(x)
        if (objA.Equals(objB))
            return 0;

        // Get two random numbers.
        int numberA = m_rnd.Next(1, 10);
        int numberB = m_rnd.Next(1, 10);

        // Compare them and return the results.
        if (numberA > numberB)
            return 1;
        else if (numberA < numberB)
            return -1;
        else
            return 0;

    }
}

 

I can tell how old this code is because I when I wrote it I was still using MFC-like prefixes for my class fields. Smile  Oh well, the code is still useful even if the formatting is a little outdated.

Have fun! Smile

Comments

No Comments

Leave a Comment

(required) 
(optional)
(required) 
Submit

About Martin

I work as a software engineer specializing in designing and building object-oriented business solutions for Windows platforms using C#. I have been programming professionally for roughly 20 years.

This Blog

Syndication

Terms of Service | Privacy Statement