使用 C# 按降序排列陣列


宣告一個數組並初始化 −

int[] arr = new int[] {
   87,
   23,
   65,
   29,
   67
};

排序,使用 Sort() 方法和 CompareTo() 來進行比較並按降序顯示 −

Array.Sort < int > (arr, new Comparison < int > ((val1, val2) => val2.CompareTo(val1)));

讓我們看看完整的程式碼 −

示例

 即時演示

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

輸出

Initial Array...
87
23
65
29
67
Sorted Array in decreasing order...
87
67
65
29
23

更新於: 22-6 月 -2020

375 次瀏覽

開啟您的 職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.