dhilst

Selection Sort in PASCAL

PROGRAM Selection_Sort;

CONST len = 12;

TYPE intarray = ARRAY[1..len] OF INTEGER;

FUNCTION ssort (A: intarray): intarray;
VAR
at, i, j, smaller, tmp: integer;
newarray: intarray;
BEGIN
{ copy array }
FOR i:=1 TO len DO
newarray[i] := A[i];

{ sort }
FOR i:=1 TO len-1 DO
BEGIN
smaller := newarray[i];
at := i;
FOR j:=i+1 TO len DO
BEGIN
IF newarray[j] < smaller THEN
BEGIN
smaller := newarray[j];
at := j;
END
END; { FOR j:=i+1 }

IF newarray[i] > smaller THEN
BEGIN { swap }
tmp := newarray[i];
newarray[i] := smaller;
newarray[at] := tmp;
END
END; { FOR i:= 0 }
ssort := newarray;
END;

{ MAIN }
VAR
a1, a2: intarray;
buf, i: integer;

BEGIN
{ read array }
FOR i:=1 TO len DO
BEGIN
writeln ('Enter a number');
readln (buf);
a1[i] := buf;
END;

{ print a1 }
FOR i:=1 TO len DO
BEGIN
write(a1[i], ' ');
END;
writeln;

{ sort }
a2 := ssort (a1);

{ print sorted a2}
FOR i:=1 TO len DO
BEGIN
write(a2[i], ' ');
END;
writeln;
END.