Данн двумерный массив n на m, состоящий из любых целых чисел.
Необходимо отсортировать массив змейкой по возрастанию(убыванию), как показано на рисунке.
Задавать дополнительный массив запрещено.
Голову уже сломал себе
uses crt;
const
n = 5;
m = 3;
type
TArray = array [1..n, 1..m] of Integer;
procedure Print(const arr: TArray);
var
i, j: integer;
begin
for i := 1 to n do begin
writeln;
for j := 1 to m do begin
write(arr[i, j]:4);
end;
end;
end;
procedure Create(var arr: TArray);
var
i, j, value: integer;
begin
value := 1;
i := 1;
j := 1;
arr[i, j] := value;
repeat
if j < m then begin
inc(j);
inc(value);
arr[i, j] := value;
end else begin
inc(i);
inc(value);
arr[i, j] := value;
end;
while (j > 1) and (i < n) do begin
dec(j);
inc(i);
inc(value);
arr[i, j] := value;
end;
if i < n then begin
inc(i);
inc(value);
arr[i, j] := value;
end else if j < m then begin
inc(j);
inc(value);
arr[i, j] := value;
end;
while (i > 1) and (j < m) do begin
dec(i);
inc(j);
inc(value);
arr[i, j] := value;
end;
until (i = n) and (j = m);
end;
var
arr: TArray;
begin
clrscr;
Create(arr);
Print(arr);
readln;
end.
const
max_col = 6;
max_row = 4;
type
tdirection = (right, left_down, down, right_up);
const
delta: array[tdirection] of record X, Y: integer end =
( (X: 1; Y: 0), (X:-1; Y: 1), (X: 0; Y: 1), (X: 1; Y:-1) );
function get_next(var dir: tdirection; var col, row: integer): boolean;
var
new_col, new_row: integer;
ok: boolean;
begin
get_next := false;
if (row = max_row) and (col = max_col) then exit;
case dir of
right:
if row = 1 then dir := left_down
else dir := right_up;
down:
if col = 1 then dir := right_up
else dir := left_down;
end;
repeat
new_col := col + delta[dir].x; new_row := row + delta[dir].y;
ok := (new_col >= 1) and (new_col <= max_col) and
(new_row >= 1) and (new_row <= max_row);
if not ok then
case dir of
right: dir := down;
left_down: dir := down;
down: dir := right;
right_up: dir := right;
end;
until ok;
col := new_col; row := new_row;
get_next := true;
end;
var
a: array[1 .. max_row, 1 .. max_col] of integer;
dir: tdirection;
i, j,
_col, _row,
first_row, first_col, mx_row, mx_col: integer;
value: integer;
T: integer;
begin
for _row := 1 to max_row do
for _col := 1 to max_col do
a[_row, _col] := random(20);
for i := 1 to max_row * max_col - 1 do begin
_col := 1; _row := 1;
dir := right_up;
for j := 1 to pred(i) do get_next(dir, _col, _row);
first_col := _col; first_row := _row;
mx_row := first_row; mx_col := first_col;
repeat
if a[mx_row, mx_col] > a[_row, _col] then begin
mx_row := _row; mx_col := _col;
end
until not get_next(dir, _col, _row);
T := a[first_row, first_col];
a[first_row, first_col] := a[mx_row, mx_col];
a[mx_row, mx_col] := T;
end;
for _row := 1 to max_row do begin
for _col := 1 to max_col do begin
write(a[_row, _col]:4);
end;
writeln;
end;
end.
const
delta: array[tdirection] of record X, Y: integer end =
( (X: 1; Y: 0), (X:-1; Y: 1), (X: 0; Y: 1), (X: 1; Y:-1) );