1

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

1
  • 1
    sorted = true; mis-placed. Commented Sep 29, 2015 at 16:20

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

-1

Why not just do:

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

1 Comment

Because... he stated in his question, that for reasons he didn't want to go into, he needs to do this in his own code, as opposed to a quick one-line solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.