PHP: Sort a list

Read a list, put it in order, and find its ends.

What to build

A program that sorts numbers.

Requirements

  • Read n, then n integers on one line.
  • Print Sorted: followed by the numbers in increasing order separated by spaces, then Largest: X and Smallest: Y.

Input

Line 1: n. Line 2: n integers.

Output

Three lines.

Constraints

1 ≤ n ≤ 100; numbers between -100000 and 100000.

Example

Input:

5
3 1 4 1 5

Output:

Sorted: 1 1 3 4 5
Largest: 5
Smallest: 1

Why it works

sort changes the array to increasing order, so the ends are also its first and last items.

Examples

Example 1 · Input
5
3 1 4 1 5
Expected output
Sorted: 1 1 3 4 5
Largest: 5
Smallest: 1
Example 2 · Input
3
-2 0 -9
Expected output
Sorted: -9 -2 0
Largest: 0
Smallest: -9

Hints

Hint 1

Turn the second line into an array of ints, as in the earlier lessons.

Hint 2

sort() orders it, max and min give the ends, and implode joins it.

Solution

Show one correct solution (try it yourself first)
<?php
$n = (int) trim(fgets(STDIN));
$a = array_map('intval', explode(" ", trim(fgets(STDIN))));
sort($a);
echo "Sorted: ", implode(" ", $a), "\n";
echo "Largest: ", max($a), "\n";
echo "Smallest: ", min($a), "\n";

▶ Open this solution in the compiler

Lesson: Arrays →