D
D
Dmitry2021-07-28 17:25:36
Algorithms
Dmitry, 2021-07-28 17:25:36

I have an array of numbers. Do I need to sort the odd numbers in ascending order, leaving the even numbers in their original positions?

Honestly, I don’t understand what the problem is, since my array floor is filled with zeros when outputting, the task is very easy, so it seems to me that just the code will be enough to identify the error.

static int[] SortArray(int[] array)
        {
            var result = new int[array.Length];
            int count = 0;
            for (int i = 0; i < array.Length; i++)
            {
                if ((array[i] & 1) != 0)
                {
                    array[i] = result[count];
                    count++;
                }
            }
            Array.Sort(result);
            int temp;

            for (int i = 0; i < array.Length-1; i++)
            {
                if ((array[i] % 1)==0)
                {
                    temp = result[i];
                    result[i] = array[i];
                    result[i + 1] = temp;
                }
            }
            return result;
        }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
edward_freedom, 2021-07-28
@roflanPominki

Regular bubble sort

var array = new[] { 55, 2, 9, 99, 12, 13, 23, 32, 5, 11, 1 };

            for (var first = 0; first < array.Length; first++)
            {
                for (var second = first; second < array.Length; second++)
                {
                    if (array[first] % 2 == 1 && array[second] % 2 == 1 && array[first] > array[second])
                    {
                        var temp = array[first];
                        array[first] = array[second];
                        array[second] = temp;
                    }
                }
            }

I
Ilya, 2021-07-28
@sarapinit

At least this is always true. if ((array[i] % 1)==0)
You need to use the remainder of division by 2))
It will be 0 for even and 1 for odd

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question