Khai báo một mảng và khởi tạo -
int[] arr = new int[] {
87,
23,
65,
29,
67
}; Để sắp xếp, hãy sử dụng phương thức Sort () và CompareTo () để so sánh và hiển thị theo thứ tự giảm dần -
Array.Sort < int > (arr, new Comparison < int > ((val1, val2) => val2.CompareTo(val1)));
Hãy cho chúng tôi xem mã hoàn chỉnh -
Ví dụ
using System;
using System.Collections.Generic;
using System.Text;
public class Demo {
public static void Main(string[] args) {
int[] arr = new int[] {
87,
23,
65,
29,
67
};
// Initial Array
Console.WriteLine("Initial Array...");
foreach(int items in arr) {
Console.WriteLine(items);
}
Array.Sort < int > (arr, new Comparison < int > ((val1, val2) => val2.CompareTo(val1)));
// Sorted Array
Console.WriteLine("Sorted Array in decreasing order...");
foreach(int items in arr) {
Console.WriteLine(items);
}
}
} Đầu ra
Initial Array... 87 23 65 29 67 Sorted Array in decreasing order... 87 67 65 29 23