Vector ascending order c#

Asked

Viewed 3,268 times

3

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();

2 answers

3

Another change is to use the Linq which 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);
}

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

Here’s an example working: .NET Fiddle

1


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

    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 + " ");

By following your code, to order only the impairments 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();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.