看到各大语言都有了,怎么能没有C#?

思路:同样是给牌赋权重,转换成对权重的排序。用最简单的冒泡排序实现。另外不用转换成权重也是很简单的,可以先对花色进行分组,对每个组进行排序,再对分组的key进行排序。

优点:用C#实现的话,至少可以显得OO一点。另外排序算法是与具体对象无关的,是个通用的算法。

先定义Card类,以及相关枚举:

class Card
{
    public CardSuit Suit { get; private set; }
    public CardValue Value { get; private set; }
    public int Weight { get { return (int)Suit * (int)Value; } }
    Card(CardSuit suit, CardValue value)
    {
        Suit = suit;
        Value = value;
    }
    public static Card Of(CardSuit suit, CardValue value)
    {
        return new Card(suit, value);
    }
    public override string ToString()
    {
        return Suit.ToString() + Value.ToString();
    }
}

enum CardSuit
{
    Spade = 1, Heart = 10, Club = 100, Diamond = 1000
}

enum CardValue
{ 
    Tow = 2, Three = 3, Four = 4, Five = 5, Six = 6, Seven = 7, Eight = 8, Nine = 9, Ten = 10, Jack = 11, Queen = 12, King = 13, Ace = 14
}

与具体对象无关的冒泡排序:

static TSource[] BubbleSort<TSource, TKey>(TSource[] elements, Func<TSource, TKey> keySelector)
{
    TSource tempElement;
    Comparer<TKey> comparer = Comparer<TKey>.Default;
    int j = elements.Length;
    while (j > 0)
    {
        for (int i = 0; i < j -1; i++)
        {
            if (comparer.Compare(keySelector(elements[i]), keySelector(elements[i + 1])) > 0)
            {
                tempElement = elements[i];
                elements[i] = elements[i + 1];
                elements[i + 1] = tempElement;
            }
        }
        j--;
    }
    return elements;
}  

获取乱序扑克的算法要复杂得多了,这个前两天左耳朵耗子讨论过。不过由于题目中规定乱序扑克是给定的条件,所以就无需担心这一点了。其余代码如下:

static void Main(string[] args)
{
    var cards = SortedCard();
    foreach (var card in cards)
    {
        Console.WriteLine(card);
    }
    Console.ReadLine();
}

static Card[] SortedCard()
{
    var cards = GetCards();
    return BubbleSort(cards, card => card.Weight);
}

static Card[] GetCards()
{
    var cards = new Card[] { Card.Of(CardSuit.Club, CardValue.Seven), 
                                Card.Of(CardSuit.Heart, CardValue.Jack),
                                Card.Of(CardSuit.Spade, CardValue.Ace),
                                Card.Of(CardSuit.Heart, CardValue.Tow),
                                Card.Of(CardSuit.Club, CardValue.King),
                                Card.Of(CardSuit.Diamond, CardValue.Ace),
                                Card.Of(CardSuit.Diamond, CardValue.Five),
                                Card.Of(CardSuit.Spade, CardValue.Nine),
                                // other cards...
    };
    return cards;
}