vector sorting
partial sorting
algorithm optimization
programming techniques
data structures

Sort a vector in which the n first elements have been already sorted?

Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms

Introduction

Knowing that the first n elements of a vector are already sorted sounds useful, but whether it helps depends on what you know about the remaining elements. If the tail is arbitrary and unsorted, there is no general magical shortcut that beats full sorting asymptotically for all comparison-based inputs, though certain practical strategies can exploit the sorted prefix in specific cases.

The First Question To Ask

You need to distinguish between these situations:

  • the first n elements are sorted and the rest are arbitrary
  • the first n elements are sorted and the rest are also sorted separately
  • the unsorted suffix is very small
  • each new element is appended one at a time to an already sorted prefix

These cases have different best solutions.

If The Suffix Is Arbitrary

If elements after position n - 1 are completely unsorted, the safe general answer is usually to sort the whole vector with the standard library.

cpp
1#include <algorithm>
2#include <vector>
3
4std::vector<int> v = {1, 3, 5, 7, 4, 9, 2, 8};
5std::sort(v.begin(), v.end());

Why is this often still correct? Because the unsorted suffix can contain any values, including values smaller than the already sorted prefix. That destroys the simple merge structure.

If You Append One Element At A Time

If the vector is sorted except for one new appended element, insertion is better than re-sorting everything.

cpp
1#include <algorithm>
2#include <vector>
3
4std::vector<int> v = {1, 3, 5, 7, 4};
5auto pos = std::upper_bound(v.begin(), v.end() - 1, v.back());
6std::rotate(pos, v.end() - 1, v.end());

This works because only one value is out of place. The sorted prefix gives you a binary-search insertion point.

If The Tail Is Also Sorted

If the vector really contains two sorted runs, then merging is the right tool.

cpp
1#include <algorithm>
2#include <vector>
3
4std::vector<int> v = {1, 3, 5, 7, 2, 4, 6, 8};
5std::inplace_merge(v.begin(), v.begin() + 4, v.end());

This is much faster than a general full sort because the structure is stronger: both halves are already sorted.

If The Unsorted Tail Is Small

When the unsorted suffix is tiny, insertion-based strategies can be practical even if the suffix itself is not internally sorted. You can process each tail element and insert it into the prefix.

cpp
1#include <algorithm>
2#include <vector>
3
4void insert_tail(std::vector<int>& v, std::size_t n) {
5    for (std::size_t i = n; i < v.size(); ++i) {
6        auto pos = std::upper_bound(v.begin(), v.begin() + i, v[i]);
7        std::rotate(pos, v.begin() + i, v.begin() + i + 1);
8    }
9}

This is useful when the tail length is small enough that repeated insertion costs are acceptable.

The Algorithmic Reality

The phrase "first n elements are sorted" alone does not imply a globally easier problem. Without more structure, the unsorted suffix may still force almost full sorting work.

That is why standard sorting algorithms such as Timsort or introsort remain strong defaults. They already exploit existing order when they detect it, so using the standard library is often both simpler and fast.

Common Pitfalls

The most common mistake is assuming a sorted prefix always implies a merge problem. It does not unless the remaining suffix is also sorted or otherwise constrained.

Another mistake is hand-writing a complex partial-sort algorithm when std::sort already performs well and is easier to trust.

A third issue is ignoring the distribution of the unsorted elements. A tiny suffix and a half-unsorted vector are very different engineering situations.

Summary

  • A sorted prefix only helps if you know something useful about the remaining elements.
  • If the suffix is arbitrary, full sorting is often still the right general solution.
  • If only one appended value is out of place, binary-search insertion works well.
  • If both parts are sorted, use merge or std::inplace_merge.
  • Choose the algorithm based on the actual structure, not on the prefix fact alone.

Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms