Collect and sort square numbers in ascending order from three lists: Difference between revisions
Content added Content deleted
Walterpachl (talk | contribs) m (fix braces) |
(→{{header|ALGOL 68}}: Use new ALGOL 68-rows library) |
||
Line 29: | Line 29: | ||
=={{header|ALGOL 68}}== |
=={{header|ALGOL 68}}== |
||
{{libheader|ALGOL 68-rows}} |
|||
<lang algol68>BEGIN # construct a list of the squares from some other lists # |
<lang algol68>BEGIN # construct a list of the squares from some other lists # |
||
# lists are represented by arrays in this sample # |
# lists are represented by arrays in this sample # |
||
# displays a list of numbers # |
|||
PR read "rows.incl.a68" PR # sorting and printing utilities # |
|||
PROC show = ( []INT list )VOID: |
|||
FOR i FROM LWB list TO UPB list DO print( ( " ", whole( list[ i ], 0 ) ) ) OD; |
|||
# in-place quick sort an array of integers # |
|||
PROC quicksort = ( REF[]INT a, INT lb, ub )VOID: |
|||
IF ub > lb THEN |
|||
# more than one element, so must sort # |
|||
INT left := lb; |
|||
INT right := ub; |
|||
# choosing the middle element of the array as the pivot # |
|||
INT pivot := a[ left + ( ( right + 1 ) - left ) OVER 2 ]; |
|||
WHILE |
|||
WHILE IF left <= ub THEN a[ left ] < pivot ELSE FALSE FI DO left +:= 1 OD; |
|||
WHILE IF right >= lb THEN a[ right ] > pivot ELSE FALSE FI DO right -:= 1 OD; |
|||
left <= right |
|||
DO |
|||
INT t := a[ left ]; |
|||
a[ left ] := a[ right ]; |
|||
a[ right ] := t; |
|||
left +:= 1; |
|||
right -:= 1 |
|||
OD; |
|||
quicksort( a, lb, right ); |
|||
quicksort( a, left, ub ) |
|||
FI # quicksort # ; |
|||
# construct the lists of numbers required by the task # |
# construct the lists of numbers required by the task # |
||
Line 62: | Line 39: | ||
, ( 75, 121, 75, 144, 35, 16, 46, 35 ) |
, ( 75, 121, 75, 144, 35, 16, 46, 35 ) |
||
); |
); |
||
# find the elements of the lists that are squares # |
# find the elements of the lists that are squares # |
||
INT r pos := 0; |
INT r pos := 0; |
||
REF[]INT |
REF[]INT squares := HEAP[ 1 : 0 ]INT; # start with an empty list # |
||
FOR i FROM LWB list TO UPB list DO |
FOR i FROM LWB list TO UPB list DO |
||
FOR j FROM LWB list[ i ] TO UPB list[ i ] DO |
FOR j FROM LWB list[ i ] TO UPB list[ i ] DO |
||
Line 72: | Line 49: | ||
THEN # have a square # |
THEN # have a square # |
||
r pos +:= 1; |
r pos +:= 1; |
||
IF r pos > UPB |
IF r pos > UPB squares THEN |
||
# the |
# the squares array isn't big enough - make a larger one # |
||
REF[]INT new |
REF[]INT new squares |
||
:= HEAP[ 1 : UPB squares + 10 ]INT; |
|||
new squares[ 1 : UPB squares ] := squares; |
|||
squares := new squares |
|||
FI; |
FI; |
||
squares[ r pos ] := n |
|||
FI |
FI |
||
OD |
OD |
||
OD; |
OD; |
||
QUICKSORT squares FROMELEMENT 1 TOELEMENT r pos; |
|||
quicksort( result, 1, r pos ); # sort the squares # |
|||
SHOW squares[ 1 : r pos ] |
|||
END</lang> |
END</lang> |
||
{{out}} |
{{out}} |