Sort months ( with strings ) algorithm

前端 未结 10 1270
深忆病人
深忆病人 2021-01-18 03:42

I have this months array:

[\"January\", \"March\", \"December\" , \"October\" ]

And I want to have it sorted like this:

[\"         


        
10条回答
  •  生来不讨喜
    2021-01-18 04:06

    Have an array with the proper sort, and sort based on it.

    Another solution (if your language supports it) is to have an associative array from month names to numbers (1..12) and use a custom comparator running sort on your array.

    Solution in Perl :D

    my @mon = qw( January February March April May June July August September October November December );
    my $mon;
    @{$mon}{@mon} = (0..$#mon);
    
    sub by_month {
        $mon->{$a} <=> $mon->{$b};
    }
    
    sort by_month @data_to_sort
    

    (although I'm sure a golfer could do that in < 30 characters)

    And here's a solution in plain C : http://www.pnambic.com/CPS/SortAnal/html/MonOrder.html

提交回复
热议问题