Vector ascending order c # [closed]

2

How to put odd numbers in ascending order?

int c = 0;
int[] numeros = { 10, 5, 20, 60, 1, 5, 8, 30, 11, 20, 25, 30, 50 };
Console.Write("Números pares");
foreach (int num in numeros)
{
    if (num % 2 == 0)
    {
        Console.Write(num + ", ");
    }
    else
    {
        c += num;
    }
}
Console.WriteLine("\n Soma dos numeros impares " + c);

Console.ReadKey();
    
asked by anonymous 04.09.2017 / 09:20

2 answers

1

Well the title of your question says that you want to sort the vector. But the posted code prints the pairs and adds the odd ones. Here is an answer to what was asked, ordering a vector of int . If you want to only place the odd ones in ascending order, follow the logic of separating them and placing them in a list then use this Array.Sort(numeros); to sort.

    int[] numeros = { 10, 5, 20, 60, 1, 5, 8, 30, 11, 20, 25, 30, 50 };
    Console.Write("Números ordenados");
    Array.Sort(numeros);
    // Escrevendo array
    foreach (int i in numeros) Console.Write(i + " ");

Following your code , just to sort the odd ones would look like this:

    int c = 0;
    List numeros = new List(){ 10, 5, 20, 60, 1, 5, 8, 30, 11, 20, 25, 30, 50 };
    List impares = new List();
    Console.Write("Números pares");
    foreach (int num in numeros)
    {
        if (num % 2 == 0)
        {
            Console.Write(num + ", ");
        }
        else
        {
           impares.Add(num);
        }
    }
    Array.Sort(impares);
    Console.WriteLine("\n numeros impares ordenados");
    foreach (int ordImp in impares)
    {
        System.Console.WriteLine(ordImp);
    }
        Console.ReadKey();
    
04.09.2017 / 10:18
3

Another alteration is to use the Linq that is very compact:

int[] numeros = { 10, 5, 20, 60, 1, 5, 8, 30, 11, 20, 25, 30, 50 };
int[] numerosImparesOrdenados = numeros.Where(x => x % 2 != 0).OrderBy(i => i).ToArray();

foreach(var numero in numerosImparesOrdenados)
{
     Console.WriteLine(numero);
}

No Linq I used Where to filter the odd, then OrderBy to sort in ascending order, and at the end, ToArray to return a new array.

Here's an example working: .NET Fiddle

    
04.09.2017 / 13:43