C# アルゴリズム 選択ソート

久しぶりにアルゴリズム

 

モンテカルロ法 と バケットソートはいいソースが見つからず

まだ理解できなかったよー(泣)

 

久しぶりに アルゴリズムやってみる。

 

選択ソート

基準となる数値を選択し、大小を比較して整列していく。

 

今後の課題、メソッドとかを使い倒して纏める。

 

参考

d.hatena.ne.jp

 

qiita.com

using System;
using System.Collections;
using System.Collections.Generic;

static class Algorithms
{
    private static void Swap<T>(ref T x, ref T y)
    {
        T tmp = x;
        x = y;
        y = tmp;
    }

    public static void SelectionSort<T>(T[] arr, Comparison<T> comparison)
    {
        for (Int32 i = 0; i < arr.Length - 1; i++)
        {
            Int32 min = i;
            for (Int32 j = i + 1; j < arr.Length; j++)
            {
                if (comparison(arr[j], arr[min]) < 0)
                {
                    min = j;
                }
            }
            Swap(ref arr[i], ref arr[min]);
        }
    }
}

class MainClass
{
    static void Main(string[] args)
    {
        Int32[] arr = { 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 };
        Algorithms.SelectionSort(arr, 
            delegate(Int32 x, Int32 y) { return x.CompareTo(y); });
        Array.ForEach(arr, delegate(Int32 n) { Console.WriteLine(n); });
    }
}