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

ALDS1_1_A: Insertion Sort


問題へのリンク


C#のソース

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

// Q002 挿入ソート https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_1_A&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 2 4 6 1 3");
            //5 2 4 6 1 3
            //2 5 4 6 1 3
            //2 4 5 6 1 3
            //2 4 5 6 1 3
            //1 2 4 5 6 3
            //1 2 3 4 5 6
        }
        else if (InputPattern == "Input2") {
            WillReturn.Add("3");
            WillReturn.Add("1 2 3");
            //1 2 3
            //1 2 3
            //1 2 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();

        InsertionSort(AArr);
    }

    static void InsertionSort(int[] pA)
    {
        Console.WriteLine(string.Join(" ", Array.ConvertAll(pA, pX => pX.ToString())));
        for (int I = 1; I <= pA.GetUpperBound(0); I++) {
            int V = pA[I];
            int J = I - 1;
            while (J >= 0 && pA[J] > V) {
                pA[J + 1] = pA[J];
                J--;
            }
            pA[J + 1] = V;

            Console.WriteLine(string.Join(" ", Array.ConvertAll(pA, pX => pX.ToString())));
        }
    }
}


解説

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