2017-07-30 54 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说:“使用搜索更长一点”:)祝你好运 –

相关问题