AOJ本の読書メモ
AOJ
次のAOJの問題へ
前のAOJの問題へ
ALDS1_2_A: Bubble Sort
C#のソース
using System;
using System.Collections.Generic;
using System.Linq;
// Q003 バブルソート https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_2_A&lang=jp
class Program
{
static string InputPattern = "InputX";
static List<string> GetInputList()
{
var WillReturn = new List<string>();
if (InputPattern == "Input1") {
WillReturn.Add("5");
WillReturn.Add("5 3 2 4 1");
//1 2 3 4 5
//8
}
else if (InputPattern == "Input2") {
WillReturn.Add("6");
WillReturn.Add("5 2 4 6 1 3");
//1 2 3 4 5 6
//9
}
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 = BubbleSort(AArr);
Console.WriteLine(string.Join(" ", Array.ConvertAll(AArr, pX => pX.ToString())));
Console.WriteLine(ChangeCnt);
}
static int BubbleSort(int[] pA)
{
int ChangeCnt = 0;
bool flag = true;
while (flag) {
flag = false;
for (int I = pA.GetUpperBound(0); 1 <= I; I--) {
if (pA[I] < pA[I - 1]) {
int Swap = pA[I];
pA[I] = pA[I - 1];
pA[I - 1] = Swap;
ChangeCnt++;
flag = true;
}
}
}
return ChangeCnt;
}
}
解説
疑似コードをC#で実装してます。