Sort by Even and Odd numbers

前端 未结 6 1086
故里飘歌
故里飘歌 2021-01-20 16:45

I would like to know is it possible to sort number by even or odd using the std::sort function.

I have the following codes but i am not sure how to implement in the

6条回答
  •  粉色の甜心
    2021-01-20 17:21

    In C# it is even simpler:

     class Program 
        {
            static void Main()
            {
              int[] numbers = { 1, 2, 3, 4, 5,6,7,8,9,10,11,12,13,14 };
    
             //using delegate
              Array.Sort (numbers, (x, y) => x % 2 == y % 2 ? 0 : x % 2 == 1 ? -1 : 1);
    
              Array.ForEach(numbers, x => Console.Write(x));
              Console.WriteLine("");
    
             //using custom comparer
              CustomComparer comparer = new CustomComparer();
              Array.Sort(numbers, comparer);
              Array.ForEach(numbers, x => Console.Write(x));
              Console.WriteLine("");
    
              //using lambda
              int[] items = numbers.OrderBy(x => x % 2 == 0).ThenBy(x => x % 2).ToArray();
    
              Console.WriteLine("");
              Array.ForEach(items, x => Console.Write(x));
            }
    
            public int Compare(int x, int y)
            {
                return x % 2 == y % 2 ? 0 : x % 2 == 1 ? -1 : 1;
            }
        }
    
        public class CustomComparer : IComparer
        {
            int IComparer.Compare(int x, int y)
            {
                return x % 2 == y % 2 ? 0 : x % 2 == 1 ? -1 : 1;
            }
        }
    

提交回复
热议问题