PKU 1804-Brainman

問題概要

バブルソートの交換の回数を求めよ

解法

Nが小さいので普通にバブルソートする

実装(Pascal)

program pku1804;

var
  n:Longint;
  i,j:Longint;
  ans:Longint;
  testcase:Longint;
  a:array[0..999] of Longint;
  tc,tmp:Longint;
begin
  read(testcase);
  for tc:=1 to testcase do begin
    read(n);
    for i:=0 to n-1 do begin
      read(a[i])
    end;
    ans:=0;
    for i:=0 to n-1 do begin
      for j:=0 to n-2 do begin
        if a[j]>a[j+1] then begin
          tmp:=a[j];
          a[j]:=a[j+1];
          a[j+1]:=tmp;
          ans:=ans+1;
        end;
      end;
    end;
    writeln('Scenario #',tc,':');
    writeln(ans);
    writeln();
  end;
end.