Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Sắp xếp mảng giảm dần trong C#


Để sắp xếp mảng theo thứ tự giảm dần trong C#, trước tiên dùng Array.Sort() để sắp xếp tăng dần, sau đó dùng Array.Reverse() để đảo ngược.

Ví dụ

using System;

namespace Demo
{
    public class MyApplication
    {
        public static void Main(string[] args)
        {
            int[] list = { 98, 23, 97, 36, 77 };
            
            Console.WriteLine("Mảng chưa sắp xếp:");
            foreach (int i in list)
                Console.Write(i + " ");
            
            // Sắp xếp tăng dần
            Array.Sort(list);
            
            // Đảo ngược để thành giảm dần
            Array.Reverse(list);
            
            Console.WriteLine("\nMảng sắp xếp giảm dần:");
            for (int i = 0; i < list.Length; i++)
                Console.Write(list[i] + " ");
        }
    }
}

Kết quả

Mảng chưa sắp xếp: 98 23 97 36 77
Mảng sắp xếp giảm dần: 98 97 77 36 23

Các cách khác

1. LINQ OrderByDescending

using System.Linq;
var sorted = list.OrderByDescending(x => x).ToArray();

2. IComparer tùy chỉnh

Array.Sort(list, new Comparison((a, b) => b.CompareTo(a)));

3. Delegate (C# 2.0+)

Array.Sort(list, delegate(int a, int b) { return b.CompareTo(a); });

Lưu ý: Array.Reverse chỉ đảo ngược thứ tự, không sắp xếp. Phải Sort trước rồi Reverse.