C++ Sorting Algorithms

Sorting algorithms arrange data into a chosen order, such as smallest to largest or alphabetically. In C++, sorting is useful before displaying data, searching with binary search, removing duplicates, or ranking items.

There are many sorting algorithms, but they all make comparisons and move elements until the collection is ordered.

What Sorting Does

A sorting algorithm receives a collection and rearranges its elements. For numbers, ascending order means each value is less than or equal to the value after it. For strings, the default order is usually lexicographic, which is similar to dictionary order.

Some sorting algorithms are easy to understand but slow for large data. Others are more complex but much faster. In everyday C++, you usually use std::sort(), but learning a simple algorithm first makes the idea clear.

Selection Sort

Selection sort is a beginner-friendly sorting algorithm. It repeatedly finds the smallest value in the unsorted part of the collection and swaps it into the next correct position.

The algorithm works, but it is not efficient for large vectors because it uses nested loops. Its time complexity is O(n * n).

#include <iostream>
#include <vector>

void printValues(const std::vector<int>& values) {
    for (int value : values) {
        std::cout << value << " ";
    }
    std::cout << std::endl;
}

void selectionSort(std::vector<int>& values) {
    for (int i = 0; i < static_cast<int>(values.size()) - 1; i++) {
        int smallestIndex = i;

        for (int j = i + 1; j < static_cast<int>(values.size()); j++) {
            if (values[j] < values[smallestIndex]) {
                smallestIndex = j;
            }
        }

        int temp = values[i];
        values[i] = values[smallestIndex];
        values[smallestIndex] = temp;
    }
}

int main(void) {
    std::vector<int> numbers = {29, 10, 14, 37, 13};

    std::cout << "Before sorting:" << std::endl;
    printValues(numbers);

    selectionSort(numbers);

    std::cout << "After sorting:" << std::endl;
    printValues(numbers);

    return 0;
}

Output:

Before sorting:
29 10 14 37 13 
After sorting:
10 13 14 29 37 

How Selection Sort Works

The outer loop chooses the position that should receive the next smallest value. The inner loop scans the remaining unsorted values and remembers the index of the smallest one.

After the inner loop finishes, the program swaps the value at i with the smallest value found. After the first pass, the smallest value is at index 0. After the second pass, the two smallest values are in place, and so on.

Using std::sort

For real programs, prefer std::sort() from <algorithm>. It is well-tested, fast, and works with iterator ranges such as values.begin(), values.end().

By default, std::sort() sorts in ascending order. You can also pass a comparison function or lambda to choose a custom order.

#include <algorithm>
#include <iiostream>
#include <string>
#include <vector>

int main(void) {
    std::vector<std::string> names = {"Nora", "Max", "Alexander", "Mia"};

    std::sort(names.begin(), names.end(), [](const std::string& a, const std::string& b) {
        return a.length() < b.length();
    });

    for (const std::string& name : names) {
        std::cout << name << std::endl;
    }

    return 0;
}

Output:

Max
Mia
Nora
Alexander

The lambda receives two names and returns true when the first name should come before the second. Here, shorter names come first.

Common Sorting Algorithms

Algorithm Basic idea Typical note
Bubble sort Repeatedly swap neighboring values that are out of order Simple, but slow
Selection sort Select the smallest remaining value and move it into place Easy to trace
Insertion sort Insert each value into the correct position in a growing sorted part Good for small or nearly sorted data
Merge sort Split, sort smaller parts, then merge them Efficient and stable when implemented that way
Quick sort Partition around a pivot value Fast in practice with good pivot choices

Choosing a Sort

Use simple algorithms when you are learning or when you need to explain every step. Use std::sort() for normal C++ code. It communicates your intent clearly and avoids mistakes in hand-written sorting logic.

  • Use ascending order when smaller values should come first.
  • Use a custom comparison when sorting by length, score, date, or another rule.
  • Sort before binary search, because binary search only works on sorted data.
  • Remember that std::sort() rearranges the original container.

Takeaway: understand simple sorting algorithms so the process is clear, but use std::sort() for most real C++ sorting tasks.