Last list item: Difference between revisions
Content added Content deleted
(→{{header|ALGOL 68}}: typo) |
(→{{header|ALGOL 68}}: Re-added sorted version, with the correct positioning of the new element (was wrong due to an error in translation)) |
||
Line 10: | Line 10: | ||
=={{header|ALGOL 68}}== |
=={{header|ALGOL 68}}== |
||
===With sorting=== |
|||
{{trans|Wren}} |
|||
<lang algol68> |
|||
BEGIN # find the last element after repeatedely adding the sum # |
|||
# of the two smallest elements and removing them # |
|||
# Quicksorts in-place the array of integers a, from lb to ub # |
|||
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 # ; |
|||
[ 1 : 9 ]INT a := ( 6, 81, 243, 14, 25, 49, 123, 69, 11 ); |
|||
INT a count := UPB a; |
|||
WHILE a count > 1 DO |
|||
quicksort( a, LWB a, a count ); |
|||
print( ( "Sorted list:" ) );FOR i TO a count DO print( ( " ", whole( a[ i ], 0 ) ) ) OD; |
|||
INT sum = a[ 1 ] + a[ 2 ]; |
|||
print( ( "; two smallest: " , whole( a[ 1 ], 0 ) |
|||
, " + ", whole( a[ 2 ], 0 ) |
|||
, " = ", whole( sum, 0 ) |
|||
, newline |
|||
) |
|||
); |
|||
a[ 1 : a count - 2 ] := a[ 3 : a count ]; |
|||
a count -:= 1 ; |
|||
a[ a count ] := sum |
|||
OD; |
|||
print( ( "Last item is ", whole( a[ 1 ], 0 ), ".", newline ) ) |
|||
END |
|||
</lang> |
|||
{{out}} |
|||
<pre> |
|||
Sorted list: 6 11 14 25 49 69 81 123 243; two smallest: 6 + 11 = 17 |
|||
Sorted list: 14 17 25 49 69 81 123 243; two smallest: 14 + 17 = 31 |
|||
Sorted list: 25 31 49 69 81 123 243; two smallest: 25 + 31 = 56 |
|||
Sorted list: 49 56 69 81 123 243; two smallest: 49 + 56 = 105 |
|||
Sorted list: 69 81 105 123 243; two smallest: 69 + 81 = 150 |
|||
Sorted list: 105 123 150 243; two smallest: 105 + 123 = 228 |
|||
Sorted list: 150 228 243; two smallest: 150 + 228 = 378 |
|||
Sorted list: 243 378; two smallest: 243 + 378 = 621 |
|||
Last item is 621. |
|||
</pre> |
|||
===Without sorting=== |
|||
Was a translation of the sorted Wren version but the sorting has been removed as per the revised task requirements. |
Was a translation of the sorted Wren version but the sorting has been removed as per the revised task requirements. |
||
<lang algol68>BEGIN # find the last element after repeatedly adding the sum # |
<lang algol68>BEGIN # find the last element after repeatedly adding the sum # |