2017-07-30 53 views
0

所以我有這種氣泡排序,第一次嘗試創建一個,這就是我所擁有的。 出於某種原因,它以奇怪的方式打印出數組。據我所知,它應該用字母排序。爲什麼我的氣泡不能正確排序我的數組?

如何正確地做一個冒泡排序而不使用LINQ或Array.Sort();這是爲了學校,所以我需要做泡沫排序算法。

這裏是它打印出來的圖像。

Here is an image of what it prints out.

class Program 
    { 
     static string[] animals = new string[] { "cat", "elephant", "tiger", "fish", "dolphin", "giraffe", "hippo", "lion", "rat", "string ray" }; 

     static void Main(string[] args) 
     { 
      BubbleSort(); 
      Console.ReadLine(); 
     } 

     private static void BubbleSort() 
     { 
      bool swap; 
      string temp; 

      string[] animals = new string[] { "cat", "elephant", "tiger", "fish", "dolphin", "giraffe", "hippo", "lion", "rat", "string ray" }; 

      for (int index = 0; index < (animals.Length - 1); index++) 
      { 
       if (string.Compare(animals[index], animals[index + 1], true) < 0) //if first number is greater then second then swap 
       { 
        //swap 
        temp = animals[index]; 
        animals[index] = animals[index + 1]; 
        animals[index + 1] = temp; 
        swap = true; 
       } 
      } 

      foreach (string item in animals) 
      { 
       Console.WriteLine(item); 
      } 
     } 
    } 
+1

您只將一個元素冒泡到它在數組中的正確位置(假設您_meant_在最後具有最小值,否則反轉您的比較運算符) - 冒泡排序需要多次通過數組。 –

+0

我將CompareTo <轉換爲CompareTo>,並將其全部添加到foreach循環中。現在,除了第二個值之外,它將打印出所有內容。 –

回答

1

對於冒泡您需要兩個嵌套的循環,因爲你正在傳遞數組不是一次,而是多次。

private static void BubbleSort() 
    { 
     string temp; 

     string[] animals = new string[] { "cat", "elephant", "tiger", "fish", "dolphin", "giraffe", "hippo", "lion", "rat", "string ray" }; 

     for (int i = 1; i < animals.Length; i++) 
     { 
      for (int j = 0; j < animals.Length - i; j++) 
      { 
       if (string.Compare(animals[j], animals[j + 1], StringComparison.Ordinal) <= 0) continue; 

       temp = animals[j]; 
       animals[j] = animals[j + 1]; 
       animals[j + 1] = temp; 
      } 
     } 

     foreach (string item in animals) 
     { 
      Console.WriteLine(item); 
     } 
    } 

PS:下一次,使用搜索的時間長一點,上面的代碼幾乎是100%從http://stackoverflow.com/questions/38624840/bubble-sort-string-array-c-sharp服用。

+0

作爲@ CRoemheld說:「使用搜索更長一點」:)祝你好運 –

相關問題