Skip to content

Instantly share code, notes, and snippets.

@ramntry
Created November 22, 2011 22:23
Show Gist options
  • Save ramntry/1387230 to your computer and use it in GitHub Desktop.
Save ramntry/1387230 to your computer and use it in GitHub Desktop.
Bubble sort statistics
const
size = 30;
multiplier = 31; { Для генератора псевдослучайных чисел }
module = 37;
{********** Array Counter Object ***********}
type arrayType = array[1..size] of integer;
arrayCounter = record
values: arrayType;
readCounter: integer;
writeCounter: integer;
end;
{ Обнуление счетчиков }
procedure refreshArrayCounter(var ac: arrayCounter);
begin
ac.readCounter := 0;
ac.writeCounter := 0;
end;
{ Обязательная инициализация объекта перед первым ипользованием }
procedure initArrayCounter(var ac: arrayCounter);
var
i: integer;
begin
refreshArrayCounter(ac);
for i := 1 to size do
ac.values[i] := 0;
end;
{ Получение элемента массива по его индексу }
function getValue(var ac: arrayCounter; index: integer): integer;
begin
inc(ac.readCounter);
getValue := ac.values[index];
end;
{ Изменение значения элемента массива с определенным индексом }
procedure setValue(var ac: arrayCounter; index: integer; value: integer);
begin
inc(ac.writeCounter);
ac.values[index] := value;
end;
{ Печать текущего состояния счетчиков обращений к массиву на чтение и на запись }
procedure printStatistics(var ac: arrayCounter);
begin
writeln('Read from array: ', ac.readCounter);
writeln('Write to array: ', ac.writeCounter);
end;
{ Печать элементов массива }
procedure printArrayCounter(var ac: arrayCounter);
var
i: integer;
begin
for i := 1 to size do
write(ac.values[i], ' ');
writeln;
end;
{^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^}
{************** Bubble Sort ****************}
procedure bubbleSort(var ac: arrayCounter);
var
i, j: integer;
tmp: integer;
begin
for i := 1 to size - 1 do
for j := 1 to size - 1 do
if getValue(ac, j) > getValue(ac, j + 1) then { Эквивалентно: if ac[j] > ac[j + 1] then }
begin
tmp := getValue(ac, j); { tmp := ac[j]; }
setValue(ac, j, getValue(ac, j + 1)); { ac[j] = ac[j + 1]; }
setValue(ac, j + 1, tmp); { ac[j + 1] = tmp; }
end;
end;
{^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^}
{************** Main Program ***************}
var
i: integer;
ac: arrayCounter;
begin
initArrayCounter(ac);
for i := 1 to size do { Заполнение массива псевдослучайными числами }
setValue(ac, i, (i * multiplier) mod module);
printArrayCounter(ac);
printStatistics(ac);
writeln;
bubbleSort(ac);
printArrayCounter(ac);
printStatistics(ac);
end.
{^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment