Tiernan Watson
Tiernan Watson

Reputation: 313

Why will this program not sort the array?

I am aware that there is a sort function available in C# to sort arrays into the correct order, but for reasons, I need to do it with my own code.

I have come up with this, and some of the numbers move, but it never fully sorts. Has anyone any idea why?

static void Main(string[] args)
    {
        int[] arraySort = { 2, 5, 7, 3, 6, 3 };
        int save;
        bool sorted = false;

        while(sorted == false) {
            for (int i = 0; i < (arraySort.Length - 1); i++)
            {
                sorted = true;
                if (arraySort[i] > arraySort[i + 1])
                {
                    save = arraySort[i];
                    arraySort[i] = arraySort[i + 1];
                    arraySort[i + 1] = save;
                    sorted = false;
                }
            }
        }

        for (int i = 0; i < arraySort.Length; i++)
        {
            Console.WriteLine(arraySort[i]);
        }
    }

My output ends up being:

2 3 5 3 6 7

Upvotes: 1

Views: 95

Answers (3)

DerekB
DerekB

Reputation: 11

Why not just do:

arraySort = arraySort.OrderBy(x => x).ToArray();

Upvotes: -1

David Constantine
David Constantine

Reputation: 587

You set sorted=true every item you iterate, You need to do sorted=true outside of the for loop, between the while and the for.

while (sorted == false) {
            sorted = true;// here seems like the right place!
            for (int i = 0; i < (arraySort.Length - 1); i++)
            {     
                if (arraySort[i] > arraySort[i + 1])
                {
                    save = arraySort[i];
                    arraySort[i] = arraySort[i + 1];
                    arraySort[i + 1] = save;
                    sorted = false;
                }
            }
        }

Upvotes: 2

James
James

Reputation: 9965

You set sorted = true inside the for loop.

So it stops as soon as the penultimate entry is less than the final entry. All other checks are ignored when validating the outer loop

Upvotes: 2

Related Questions