How to sort array odd numbers in descending order and even numbers in ascending order in C#

1 Answer

0 votes
using System;

class Program
{
    static void make_odds_negative(int[] arr) {
        int len = arr.Length;
        
        for (int i = 0; i < len; i++) 
            if (arr[i] % 2 != 0)
                arr[i] *= -1; 
    }
    static void odd_even_sort(int []arr) { 
        make_odds_negative(arr);
    
        print(arr);
        
        Array.Sort(arr); 
        
        print(arr);
      
        make_odds_negative(arr);
    } 
    
    static void print(int[] arr) {
        for (int i = 0; i < arr.Length; i++) 
            Console.Write(arr[i] + " "); 
        Console.WriteLine();    
        
    }
        
    static void Main()
    {
        int[] arr = {3, 4, 6, 1, 2, 5}; 
          
        odd_even_sort(arr); 
          
        print(arr);
    }
}


/*
run:


-3 4 6 -1 2 -5 
-5 -3 -1 2 4 6 
5 3 1 2 4 6 

*/

 



answered May 4, 2019 by avibootz
...