AOJ本の読書メモ   AOJ    次のAOJの問題へ    前のAOJの問題へ

ALDS1_2_B: Selection Sort


問題へのリンク


C#のソース

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

// Q004 選択ソート https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_2_B&lang=jp
class Program
{
    static string InputPattern = "InputX";

    static List<string> GetInputList()
    {
        var WillReturn = new List<string>();

        if (InputPattern == "Input1") {
            WillReturn.Add("6");
            WillReturn.Add("5 6 4 2 1 3");
            //1 2 3 4 5 6
            //4
        }
        else if (InputPattern == "Input2") {
            WillReturn.Add("6");
            WillReturn.Add("5 2 4 6 1 3");
            //1 2 3 4 5 6
            //3
        }
        else {
            string wkStr;
            while ((wkStr = Console.ReadLine()) != null) WillReturn.Add(wkStr);
        }
        return WillReturn;
    }

    static void Main()
    {
        List<string> InputList = GetInputList();
        int[] AArr = InputList[1].Split(' ').Select(X => int.Parse(X)).ToArray();

        int ChangeCnt = SelectionSort(AArr);
        Console.WriteLine(string.Join(" ", Array.ConvertAll(AArr, pX => pX.ToString())));
        Console.WriteLine(ChangeCnt);
    }

    static int SelectionSort(int[] pA)
    {
        int ChangeCnt = 0;
        for (int I = 0; I <= pA.GetUpperBound(0); I++) {
            int MinJ = I;
            for (int J = I; J <= pA.GetUpperBound(0); J++) {
                if (pA[J] < pA[MinJ]) {
                    MinJ = J;
                }
            }
            if (I != MinJ) {
                int Swap = pA[I];
                pA[I] = pA[MinJ];
                pA[MinJ] = Swap;
                ChangeCnt++;
            }
        }
        return ChangeCnt;
    }
}


解説

疑似コードをC#で実装してます。