SORA.GetOutput()

備忘録と捌け口とシェアと何か。

C# 配列の昇順・降順並び替え2種(Arrayを使う方法、LINQを使う方法)

Arrayの静的メソッドを使用

Array.Sortメソッドで配列を操作すると、破壊的変更となる。 → 元の配列を直接イジる。
Array.SortのアルゴリズムはQuickSort。計算時間は平均O(n log n)、ワーストO(n ^ 2)。

昇順の場合

int[] scores = new int[] {1,5,4,2,3};
Array.Sort(scores);
// {1,2,3,4,5} 
// scores = Array.Sort(scores);としなくても変更が掛かる。

降順の場合

int[] scores = new int[] {1,2,3,4,5};
Array.Sort(scores); //{1,2,3,4,5}
Array.Reverse(scores); // {5,4,3,2,1} SortしてからReverseを掛ける。共に破壊的変更。

LINQを使用

LINQで配列を操作すると、操作した結果の配列が返り値となる。→元の配列は直接イジらない。

昇順の場合

int[] scores = new int[] {1,5,4,2,3};
scores = scores.OrderBy(x => x).ToArray(); // {1,2,3,4,5} 
// scores = としないと元の配列は変更されない。

降順の場合

int[] scores = new int[] {1,5,4,2,3};
scores = scores.OrderByDescending(x => x).ToArray(); // {1,2,3,4,5} 
// scores = としないと元の配列は変更されない。