When element values change in a sorted C or C++ array, the wrong fix is to call a full sort after every update. The right fix is to remove the element from its current position, mutate it, and reinsert it into the position its new value requires. For built-in arrays, delete by shifting with memmove, update, then reinsert with a binary search plus memmove. Compare the element count against the update count and break ties toward the cheaper side. Everything else is detail that follows from that tradeoff.
Why a Full Resort Is the Wrong Reflex
An insertion sort is near-linear on an array that is already sorted except for one displaced element. Standard library sort functions are comparison sorts that run in O(n log n) time regardless of how little the input changed. That difference is enormous at scale, and it grows with n.
On a one-million-element array where n log n sorting costs roughly 20 million comparisons, a single remove-and-reinsert costs about 20 comparisons for binary search plus a memmove of contiguous memory. Even a brute-force reinsertion shift is one pass, on the order of n moves executed at memory bandwidth rather than comparator cost. The sort does work proportional to the whole array, but the update only disturbs a slice of it.
There are exceptions worth naming. Address-sanitized debug builds and non-default standard library implementations change the constants but not the asymptotics. On short arrays, below roughly two dozen elements, the constant factors dominate and the choice barely matters. The mechanism is simple: sorting ignores what you already know about the array, and after an in-place value change you know almost everything.
The Invariant: What "Sorted" Actually Means Mid-Update
A sorted array is not a property of its memory; it is a property of the relation between adjacent elements. Formally, for every index i from 0 to count minus 2, the element at i is less than or equal to the element at i+1. Mutating one element can violate at most two of those adjacent relations: the pair with its left neighbor and the pair with its right neighbor.
That locality is the whole game. A value change breaks at most two comparisons, so only a small region needs repair. In C and C++, the danger is that the compiler does not know about your invariant. It sees a plain assignment to an array slot, and it optimizes accordingly.
In C++20 and later, the compiler understands std::sort and may use that knowledge to optimize surrounding code. Hand-written insertion or shifting loops carry no such contract. If you have corrupted the ordering invisibly, the compiler has license to suppose it did not happen.
One professional caveat: with aggressive optimization, undefined behavior in an update routine can manifest as elements that sort themselves back or vanish. The array is not haunted; the optimizer exploited a broken promise. Preserve the invariant exactly, and keep the mutation and repair adjacent in the source.
Two Update Paths: Value Increases (Move Right) vs. Decreases (Move Left)
The direction of the move is determined by the sign of the change, not by which algorithm you prefer. Pick it explicitly and document it, because mixing the two paths is the most common source of off-by-one errors.
When the value increases, the element must travel right. Swap it forward past each neighbor it now exceeds, stopping when the next neighbor is greater than or equal to it. For contiguous storage, a left rotation using memmove or std::rotate moves the element to the correct slot in one pass over the affected window.
When the value decreases, the same logic runs in reverse: swap backward past each smaller neighbor, stopping when the left neighbor is less than or equal to it. A right rotation performs the move in linear time over the window size. Each swap costs a single comparison and two moves.
Duplicates complicate direction. If you need stable order among equal keys, a pure direction rule cannot guarantee it. A stable full sort preserves input order; remove-and-reinsert at the boundary between equal runs can too, if you always insert before or always after the equal block. Consistency matters more than the boundary chosen.
Plain-language version: find where the element lives, pull it out, let the gap close behind it, and drop it into the slot its new value earns.
Cost Table: Choosing a Strategy by Update Pattern
The right data structure follows from the ratio of updates to reads. The table below compares the common options by their worst-case asymptotics, not by a specific library or platform.
| Strategy | Update cost | Lookup cost | Memory overhead | Best when |
|---|---|---|---|---|
| Full resort after change | O(n log n) | O(log n) binary search | None | Rare updates, tiny n |
| Remove and insert (memmove) | O(n) moves | O(log n) binary search | None | Bulk updates, contiguous data |
| Sorted linked list | O(n) traversal | O(n) | One pointer per node | Never a default for arrays |
| Order-statistic tree | O(log n) | O(log n) | Pointers plus counters | Frequent updates, fewer scans |
| Skip list | O(log n) expected | O(log n) expected | Pointers, level metadata | Updates with scan-heavy reads |
| Binary heap | O(log n) | O(n) to find arbitrary | None | Only when minimum or maximum is read |
The counterintuitive detail: a sorted linked list seems like the natural answer for changing values, but traversing to the insertion point costs linear time with terrible cache behavior. The memmove on a contiguous array often beats it in wall-clock time well past a million elements, especially for bulk updates, because the CPU streams memory at gigabytes per second.
Use this table as a starting hypothesis, then measure on your own data. A switch is justified when the update pattern, not the data size alone, favors it.
Applying the Update Safely: A Working Pattern
Here is the skeleton for a built-in array, applying the direction rule and keeping the invariant intact:
Never sort in place while a consumer might run concurrently. Hold a lock or use a double-buffer copy so readers see either the old order or the new order, never a half-rotated array. Locate the current position with a binary search restricted to the known sorted region. Validate the result before mutating anything. Save the old value, remove the element with memmove, then mutate a local copy rather than the live slot. Compute the new insertion index on the shrunk array with a second binary search, then memmove the tail right and write the value back. If several elements change in one batch, sort the update batch first, then merge it in one linear pass rather than repeating the operation per element. After each invariant-breaking statement in the routine, compile with strict warnings and run at least one sanitizer build to catch pointer arithmetic errors.
The red-flag warnings here are worth treating as hard rules. Calling the library sort inside a hot update path is a performance bug, not a style preference. Assuming the array is sorted after a failed binary search returns a wrong index corrupts the invariant silently. Recomputing an index after a memmove from stale offset arithmetic skips or duplicates elements with no crash to warn you.
When the update routine writes to the element through a pointer that an optimizer reorders past the repair shift, the fix is to keep the read, the direction decision, and the shift as a single unbroken sequence in the source. Do not split them across helper functions that return by value and write through references separately.
In-Place Updates on Non-Trivial Types and Parallel Readers
For trivially copyable types, raw memmove is the fastest legal path and keeps the array sorted with minimal ceremony. In C++, std::array<T, N> inside a program where T is a class has additional rules: move-assignable types let the shift operations use moves that may throw, so the shift can be interrupted mid-cycle and leave the array in a state that violates the sorted invariant.
The professional move is to require a nothrow-move-assignable type, or to copy into a scratch buffer, sort the scratch, and swap the whole container. A swap exchange of two containers is constant-time in the standard library; the cost of the reorder happens once, atomically from the reader's view.
Parallel readers of the sorted array add a second invariant: no reader may observe a partially rotated state. A lock held across the shift has a linear critical section, so a lock-free reader usually demands a copy or a versioned buffer with a sequence number. The sequence number increments after the repair, and readers retry if it changed while they scanned. Such retries are bounded on any packet-priority scheme, but the sequence counter should be cheap and rarely contended.
For strings or structs moved with memmove, avoid the shortcut. memmove on a type with a non-trivial copy constructor is undefined behavior in C++. Use std::rotate or move assignment and verify that swapping never touches the moved-from element afterward.
When Sorted Arrays Stop Being the Answer and What to Watch
The sorted array is the fastest structure for reads and the slowest for updates, so a workload dominated by updates should not use it. An order-statistic tree handles updates in logarithmic time and answers rank queries directly, but it pays for that with pointer chasing and cache misses. A binary heap maintains only a partial order, which keeps the sorted-read invariant entirely absent but supports cheap extraction of the extreme value only.
Also re-evaluate at the boundaries. Data sizes above roughly ten million elements, with updates arriving faster than sorting and binary searching can complete, usually belong in an embedded database or an external merge pipeline rather than a hand-maintained array. Below a few hundred elements, the fastest correct code is simply to sort the whole window, and the choice of algorithm is noise.
There is an open question about tooling support rather than mechanism: standard libraries give no built-in assert that a container is sorted, and tests that only check sortedness once per run miss whole classes of corruption. A monotonicity check before every read is cheap at small sizes and practical to toggle behind a debug build. Manual validation remains the only defense against false sortedness in C and C++.
The summary lives in the opening: remove, mutate, reinsert, and choose it over a full resort whenever the element count exceeds the number of updates. Every technical choice after that is arithmetic on that trade.