Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort ascending only odd numbers in array?

Tags:

arrays

c#

sorting

I want to sort only odd numbers without moving even numbers. For example, if my input is:

[5, 3, 2, 8, 1, 4]

The expected result is:

[1, 3, 2, 8, 5, 4]

I am new to C# and I came across a challenge on the Internet that has me perplexed. I have tried for hours and I would like to learn this concept in

The challenge states:

You have an array of numbers. Your task is to sort ascending odd numbers but even numbers must be on their places. Zero isn't an odd number and you don't need to move it. If you have an empty array, you need to return it.

Here is my code so far, please take it easy on me I am in the beginning stages of programming.

public static int[] SortArray(int[] array)
{
    var dict = new Dictionary<int, int>();
    var dict2 = new Dictionary<int, int>();

    for (int i = 0; i < array.Length; i++)
    {
        int j =0;
        if (array[i] % 2 != 0)
        {
            dict.Add(array[i], i+1);
        }
        else
        {
            dict2.Add(array[i], i+1);
        }
    }
    var result = dict.OrderBy(x => x.Key);
    Dictionary<int, int> resultDic = result.Union(dict2)
      .GroupBy(x => x.Key).ToDictionary(o => o.Key, o => o.Key);
}

public static void Main()
{
    SortArray(new int[] { 5, 3, 2, 8, 1, 4});
}
like image 242
DeveViru Avatar asked Jan 19 '26 11:01

DeveViru


1 Answers

You can do this with linq by indexing the numbers before you start:

var nums = new[] { 5, 3, 2, 8, 1, 4 };
var indexedNums = nums.Select((num, idx) => new { num, idx }).ToList();

Then sorting these indexed numbers into evens and odds:

var evens = indexedNums.Where(x => x.num % 2 == 0);
var odds = indexedNums.Where(x => x.num % 2 == 1);

Sorting the odd (indexed) numbers by their value:

var sortedOdds = odds.OrderBy(x => x.num); //sort the odd numbers by their value

Zipping this sequence with the odds sequence (which is sorted by index), taking the number from sortedOdds and the index from odds

var reindexedOdds = sortedOdds.Zip(odds, (o1, o2) => new { o1.num, o2.idx });

...and throwing these reindexedOdds into a sequence with the indexed evens from above, sorting by index and then selecting out the number.

var endSequence = evens.Concat(reindexedOdds).OrderBy(x => x.idx).Select(x => x.num);
like image 96
spender Avatar answered Jan 21 '26 00:01

spender



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!