Developping for the translation industry RSS 2.0



 Wednesday, 19 December 2007

Jeff Atwood recently posted on the topic of sorting strings in a more natural order that the default string sorting gives us.  His main point is, when we’re dealing with numbers, a simple alphabetic sorting doesn’t cut it.

So. just for fun, here’s my little C# 2.0 Implementation of a more human-friendly sorter.

 

public class FriendlySorter<T> : IComparer<T>

{

    public int Compare(T x, T y)

    {

        if (x == null || y == null) return 0;

        if (x.ToString() == y.ToString()) return 0;

 

        string[] left = Regex.Split(x.ToString(), "([0-9]+)");

        string[] right = Regex.Split(y.ToString(), "([0-9]+)");

 

        int index = 0;

 

        while (true)

        {

            while (left[index] == right[index]) index++;

 

            if (left.Length == index && right.Length == index) return 0;

            if (left.Length <= index) return -1;

            if (right.Length <= index) return 1;

 

            try

            {

                return (int.Parse(left[index]) - int.Parse(right[index]));

            }

            catch

            {

                int CompareResult = String.Compare(left[index], right[index]);

                if (CompareResult != 0) return CompareResult;

            }

 

            index++;

        }

    }

}

 

The following code :

List<string> list = new List<string>();

 

list.Add("Track 1 : abc");

list.Add("Track 2 : abc");

list.Add("Track 10 : abc");

list.Add("Track 5 : abc");

list.Add("Track 11 : abc");

list.Add("Track 22 : abc");

list.Add("Track 9 : abc");

 

list.Sort(new FriendlySorter<string>());

 

Will produce the results :

Sshot-4

For small sets the performance is Ok.  But when dealing with a larger amount of data (1000+ items), the sorting performance drops a lot (I currently have 5 seconds to sort 1000 random elements).  I will probably try to enhance it in the future and update this post.

Happy holidays !

Tags:
Wednesday, 19 December 2007 18:42:12 (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
.NET | C# | Code Snippet

Navigation
Advertisement
About the author/Disclaimer

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2017
Stanislas Biron
Sign In
Statistics
Total Posts: 135
This Year: 0
This Month: 0
This Week: 0
Comments: 1
All Content © 2017, Stanislas Biron