Lesson 11 of 12

Optional: rearrange an active sequence

Use half-open algorithm ranges and preserve values while shifting, rotating, inserting, or deleting.

Sort and reverse mean different things

This is a second-reading extension. <algorithm> provides std::sort(a, a + n), which rearranges the active values into nondecreasing order. Duplicates remain, and original positions may change. The range includes its start and excludes its end.

Using a + n − 1 as the end leaves out the last active value; using a + CAPACITY includes inactive cells. For strings, pass s.begin() and s.end(). std::reverse reverses current order; it produces descending order only if the sequence was sorted first.

Both algorithms modify the supplied sequence rather than returning a new ordinary string. Sorting is more work than a simple traversal; do not sort merely to check whether the original sequence was already ordered.

C++23
#include <iostream>
#include <string>
#include <algorithm>

int main() {
    std::string s;
    std::getline(std::cin, s);
    std::sort(s.begin(), s.end());
    std::cout << s << '\n';
    std::reverse(s.begin(), s.end());
    std::cout << s << '\n';
    return 0;
}

A rotation saves the value that wraps

A one-step right rotation turns [10, 20, 30, 40] into [40, 10, 20, 30]. Save the last element, copy the remaining suffix right starting from the right end, then place the saved element at index zero.

Copying rightward from left to right overwrites future source values. Guard n > 0 before reading a[n − 1]. A rotation preserves every value and the active length, unlike a shift that discards one end and fills the other.

Insertion requires spare capacity

To insert at a position from 0 through n, require n < CAPACITY. Move a[i − 1] into a[i] from i = n downward while i > position, write the new value into the gap, then increment n.

The first write can use old index n only because a spare allocated cell exists. Insertion at position n appends without moving a suffix. Physical capacity stays fixed; active length grows.

Deletion closes the gap

For a valid position in a nonempty sequence, copy each following value left: a[i] = a[i + 1] from the deletion position while i + 1 < n. Then decrement n. The old final cell is now inactive and need not be erased.

Deletion moves left to right; insertion moves right to left. These directions preserve each source until it is read. Inserting or deleting near the front can move almost every active element, so the work grows with the sequence length.

Pause & predict

An array has capacity 5 and active length 5. Can the bounded-array insertion procedure add another element?

Choose an answer
Try it yourself

Turn the idea into code

Optional: read 0 ≤ n ≤ 1000 integers and rotate the active array right by one. Leave an empty list empty.

Give me a hint

Save the last value before shifting. Copy from right to left.

Show the explained solution

The saved value wraps into index zero, while every earlier element moves exactly one place right. The guard makes the empty case safe and a one-element list stays unchanged.

C++23
#include <iostream>

int main() {
    int a[1000]{};
    int n = 0;
    std::cin >> n;
    for (int i = 0; i < n; ++i) { std::cin >> a[i]; }
    if (n > 0) {
        int last = a[n - 1];
        for (int i = n - 1; i > 0; --i) { a[i] = a[i - 1]; }
        a[0] = last;
    }
    for (int i = 0; i < n; ++i) {
        if (i > 0) { std::cout << ' '; }
        std::cout << a[i];
    }
    std::cout << '\n';
    return 0;
}

Your notes

Ready for the next idea?

Mark complete when you can explain it yourself.

From a problem to a programIdentify the input, output, and constraints, then translate a small plan into C++.Variables, types, and remembered valuesChoose a representation, initialize it, and understand what assignment really changes.Arithmetic without surprisesPredict division and remainder, widen before multiplication, and format decimal answers.Conditions and logical decisionsBuild exclusive categories, combine comparisons, and protect operations with short-circuit logic.Optional: other ways to chooseRecognize switch for exact choices and the conditional operator for choosing a value.For loops: make repetition preciseTrace initialization, condition, body, and update—and avoid an extra iteration.While, do-while, and stopping rulesChoose a loop from its stopping condition and read the exact input format.Break, continue, and early answersDistinguish leaving a loop from skipping one iteration, without losing required input.Five patterns worth understandingUse sums, counts, best-so-far candidates, products, and flags to process a stream.Nested loops: rows and columnsTranslate a shape into two loop roles and count the total work.Take a number apart, one digit at a timeUse remainder and division to process decimal digits, including zero.Multiple cases and a debugging mindsetCombine the patterns, isolate each case, and test the boundaries that can break your idea.Arrays: give every value a placeUnderstand indices, initialization, capacity, active length, and the first safe array loop.Scan, count, search, and compareDistinguish values from positions and preserve the exact tie rule a problem asks for.Change a sequence without losing itUpdate, copy, compare, reverse, and inspect neighbours using the correct bounds.Matrices: think in two coordinatesTraverse tables, total rows and columns, inspect diagonals, and protect grid neighbours.Characters become stringsSeparate characters from numbers, then safely inspect and edit managed text.Read the text the problem actually givesChoose words or full lines, preserve empty cases, and reset only the state that needs it.Scan text: count, filter, transformBuild a result from matching characters without losing leading zeros or skipping shifted text.Join, compare, and find textLearn content comparison, lexicographical order, substring counts, and the not-found sentinel.