【问题标题】:Alphabetically sort using an insertion sort algorithm c#使用插入排序算法按字母顺序排序 c#
【发布时间】:2012-02-17 18:44:32
【问题描述】:

我一直在搜索互联网和书籍,但没有运气,所以希望有人能指出我正确的方向。

我基本上需要使用插入排序而不是内置方法按名称语句按字母顺序对对象进行排序。我尝试过使用数组和列表,但似乎无法让它工作。你会怎么做呢?

我有一个 Player 类,最近一次尝试用列表对象填充:

    public static List<Player> user = new List<Player>(); 
    private string name; //Read and Write
    private int score; //Read and Write
    private double health; //Read and Write
    private int level;  //Read and Write
    public string[] inventory = new string[30];

    public void setName(String newName)
    {
        name = newName;
    }
    public string getName()
    {
        return name;
    }
    public void setScore(int newScore)
    {
        score = newScore;
    }
    public int getScore()
    {
        return score;
    }
    public void setHealth(double newHealth)
    {
        health = newHealth;
    }
    public double getHealth()
    {
        return health;
    }
    public void setLevel(int newLevel)
    {
        level = newLevel;
    }
    public int getLevel()
    {
        return level;
    }

    public static void Saved_Player()
    {
        user.Add(new Player() { name = "Timid Bob", health = 63, level = 6, score = 2000, });
        user[0].inventory[0] = "Steel Sword";
        user[0].inventory[1] = "1mm MAW";
        user[0].inventory[2] = "Short Bow";
        user[0].inventory[0] = "Grenade";

        user.Add(new Player() {name = "Killer Bob", health = 82, level = 2, score = 1050000, });
        user[1].inventory[0] = "Glass Sword";
        user[1].inventory[1] = "250mm MAW";
        user[1].inventory[2] = "Elephant Bow";
        user[1].inventory[3] = "Rock";

等等...最多 6 个用户对象

为了对其进行排序,我尝试在另一个类 Form1 中使用以下代码:

//sudo 代码

          for(int i = 0; i < Player.user.Count; i++)
          {

            while (i index is higher than i+1 index)
            {
                swap i index with i+1 index
            }

          }  

希望是对的:/

我想我了解 PublicJoe 是如何做到的,但是您如何获取和设置对象的索引?感谢观看。

【问题讨论】:

  • 家庭作业?什么不工作?发布您的代码。
  • 如果您编辑您的问题以包含您迄今为止的最佳尝试,并解释您认为它不起作用的原因,您将获得一些帮助。
  • 如果您要进行插入排序,那不是。插入排序意味着对于每个新玩家,您将遍历您的用户列表,将新玩家与现有玩家进行比较,找到正确的插入点并将玩家插入那里。

标签: c# sorting insertion-sort


【解决方案1】:

数组不适合插入。如果您回想一下您的类,您可能会发现一种更适合插入的数据结构。

在插入排序中,您从未排序列表中取出一项,然后将其放在另一个列表的正确位置。

您似乎正在尝试做的事情似乎是某种排序选择排序。

我认为交换值的 4 行存在问题

                object temp;
                object = Player.user[Second];
                Player.user[first] = Player.user[Second];
                Player.user[(temp - 1)] = Player.user[Second];

如果我是你,我会再看一遍。

【讨论】:

  • 也许使用?:临时对象第二个对象索引 = temp 第二个对象索引 = 第一个对象索引 temp - 1 = 第二个对象索引
【解决方案2】:

如果您使用的是列表,您可以这样做:

public void InsertionSort(Player newUser)
{
    var index = users.FindLastIndex(u => u.Name <= newUser.Name);
    users.Insert(index, newUser);
}

【讨论】:

    猜你喜欢
    • 2020-10-26
    • 1970-01-01
    • 1970-01-01
    • 2020-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多