← Java from Scratch Lesson 81 of 88 · 10 XP

Algorithms

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

The Collections class holds ready-made algorithms over collections:

List<Integer> l = new ArrayList<>(List.of(5, 3, 9, 3, 1));
Collections.max(l), Collections.min(l)     // 9, 1
Collections.frequency(l, 3)                // 2
Collections.reverse(l)                     // [1, 3, 9, 3, 5]
Collections.swap(l, 0, 4)
Collections.rotate(l, 2)                   // a circular shift to the right by 2
Collections.sort(l)
Collections.binarySearch(l, 9)             // the index in a SORTED list (O(log n))
Collections.nCopies(3, "ab")               // [ab, ab, ab]
Collections.unmodifiableList(l)            // a "read-only" wrapper

For arrays the same things are in Arrays: sort, binarySearch, fill, equals.

binarySearch on an unsorted list returns garbage; if the element isn't there, it returns a negative number, -(insertion_point) - 1.

Task. Read numbers. Print: the maximum and the minimum, how many times the maximum appears, the list after rotate by 1, then the sorted list and the index of the number 7 in it using binarySearch (if it isn't there — none).

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.