为什么我的冒泡没有正确排序我的数组?

时间:2017-07-30 01:02:31

标签: c# arrays string sorting

所以我有这个泡泡排序,第一次尝试创建一个,这就是我所拥有的。 由于某种原因,它以一种奇怪的方式打印出阵列。 据我所知,应该用字母对它进行排序。

如何在不使用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 个答案:

答案 0 :(得分:1)

对于Bubblesort,你需要两个嵌套循环,因为你不是一次多次传递数组。

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