冒泡排序问题

时间:2013-11-13 01:44:14

标签: c#

我一直在尝试运行此代码时出现NullReferenceException未处理错误,并且不知道原因。 我试图按人名排序 我只用了大约4个月的c#。

    public static student[] players = new student[30];
    public struct student
    {
        public string lastname;
        public string firstname;
        public string likes;
    }

    public static void read()
    {
        StreamReader sr = new StreamReader(@"names.txt");
        int i = 0;
        while (!sr.EndOfStream)
        {
            players[i].lastname = sr.ReadLine();
            players[i].firstname = sr.ReadLine();
            players[i].likes = sr.ReadLine();
            i++;
        }
        sr.Close();
    }

        public static void sort()
        {
            //alphabetically lists players
            student temp;

            for (int i = 0; i < players.Length - 1; i++)
            {
                for (int pos = 0; pos < players.Length - 1; pos++)
                {

                    if (players[pos + 1].lastname.CompareTo(players[pos].lastname) < +0)
                    {
                        temp = players[pos + 1];
                        players[pos + 1] = players[pos];
                        players[pos] = temp;
                    }
                }
            }

        }

3 个答案:

答案 0 :(得分:1)

我可能已经抓住了NullReference

while (!sr.EndOfStream)
{
    player[i] = new student();
    players[i].lastname = sr.ReadLine();
    players[i].firstname = sr.ReadLine();
    players[i].likes = sr.ReadLine();
    i++;
}

答案 1 :(得分:1)

在比较null之前,您需要检查数组项是否为lastname

private static void Sort(Player[] players)
{
    //alphabetically lists players

    for (int i = 0; i < players.Length; i++)
    for (int pos = 0; pos < players.Length - 1; pos++)
    {
        var currentPlayer = players[pos] != null ? players[pos].LastName : null;
        var nextPlayer = players[pos + 1] != null ? players[pos + 1].LastName : null;

        if (Compare(currentPlayer, nextPlayer) > 0)
        {
            var temp = players[pos + 1];
            players[pos + 1] = players[pos];
            players[pos] = temp;
        }
    }
}

private static int Compare<T>(T current, T next)
    where T: IComparable
{
    if (current == null) return -1;
    if (next == null) return 1;
    return current.CompareTo(next);
}

答案 2 :(得分:0)

排序已经通过Enumerable.OrderByEnumerableOrderByDescending内置到.NET框架中。在您的情况下,您可以大大减少功能:

public static IOrderedEnumerable<student> sort()
{
   IOrderedEnumerable<student> orderedPlayers = players.OrderBy(p => p.lastname);
   return orderedPlayers;
}

即使lastName为空,这也会在不抛出异常的情况下对结果进行排序。