2012-02-17 137 views
0

我一直在搜索互聯網和書籍,但沒有運氣,所以希望有人能指出我在正確的方向。按字母順序排序使用插入排序算法c#

我基本上需要使用插入排序而不是內置方法按字母順序排列對象的名稱。我曾嘗試使用數組和列表,但似乎無法使其工作。你會怎麼做呢?

我有一類球員,充滿了名單的最新嘗試對象:

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類:

//須藤代碼

  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的做法,但是如何獲取和設置對象的索引?感謝您的期待。

+1

功課?什麼不起作用?發佈您的代碼。 – 2012-02-17 18:49:44

+0

http://www.publicjoe.f9.co.uk/csharp/sort00.html – Josh 2012-02-17 18:57:46

+1

如果您編輯您的問題以包括迄今爲止的最佳嘗試,並解釋爲什麼您認爲它不起作用,您會得到一些幫助它。 – 2012-02-17 19:07:32

回答

0

數組不好插入。如果您回想起您的課程,您可能會發現一個更適合插入的數據結構。

在插入排序中,您將未排序列表中的項目,然後將其放入另一個列表的正確位置。

你似乎試圖做的似乎是某種選擇排序。

我想有一個與在那裏你交換你的價值觀

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

的4條線路有問題我必須在那如果我是你第二次看。

+0

也許使用?: 溫度對象 第二個對象索引= temp 第二個對象索引=第一個對象索引 temp - 1 =第二個對象索引 – Flak714 2012-02-18 02:41:18

0

如果您使用的列表,你可以簡單地這樣做:

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