Friday, April 8, 2011

BinarySearch not having expected results

I have populated a sorted list of dates(stored as strings in the format dd/mm/yyyy) from an xml file using xpath.

However when querying the list to see if a date exists within the list I always get negative result(i.e. doesnt exist) even though i have hardcode the query string to match a date within the list.

However, when doing a string compare on the index which contains the queried string I get 0 indicating the strings are identical.

What can cause this odd behaviour?

As requested here is the code

Holidays is populated by:

while (iter.MoveNext())
        {

            XPathNavigator nav2 = iter.Current;
            XPathNodeIterator iter2 = nav2.SelectDescendants("date", "", false);
            while (iter2.MoveNext())
            {

                date = iter2.Current.ToString();
                holidays.Add(date);
            }


        }

        return holidays;

And the search is:

holidays = list.getHolidays();
if(holidays.BinarySearch(DateTime.Now.ToShortDateString()) > 0)

...

01/01/2009 25/02/2009 10/04/2009 13/04/2009 04/05/2009 25/05/2009 31/08/2009 25/12/2009 28/12/2009

above shows the xml data being used

From stackoverflow
  • I believe it has to do with the format of the strings. You list is being sorted by day, month, then year, which isn't correct.

    You need to format your strings like so:

    yyyy/mm/dd

    And then sort the list, and your search should work.

    If these were dates (as in DateTime) then the list would sort itself correctly, but since they are strings, and your format doesn't support sorting based on the natural properties of strings, your sort order is all messed up.

    CodeMonkey : your right, if i reverse the format it does work however the dates are going to be generated in dd/mm/yyyy format is there a quick way of converting this into yyyy/mm/dd ?
    Richard : @codeMonkey: Look at DateTime.ParseExact and there is a format specified for ISO format yyyy-mm-dd...
    CodeMonkey : @Richard: thanks

0 comments:

Post a Comment