Victor Jones
Victor Jones

Reputation: 13

Why isn't my bubble sort sorting my array correctly?

So I have this bubble sort, first time trying to create one and this is what I have. For some reason it's printing out the array in a weird way. It should sort it by letters as far as I know.

How do I properly do a bubble sort without using LINQ or Array.Sort(); This is for school so I need to do the bubble sort algorithm.

Here is an image of what it prints out.

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);
            }
        }
    }

Upvotes: 0

Views: 106

Answers (1)

CRoemheld
CRoemheld

Reputation: 949

For Bubblesort you need two nested loops since you are passing the Array not once but multiple times.

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: Next time, use the search a bit longer, the code above is almost 100% taken from http://stackoverflow.com/questions/38624840/bubble-sort-string-array-c-sharp.

Upvotes: 1

Related Questions