What is Sorting in C++ and Types of Sorting Algorithms
TL;DR: Sorting in C++ arranges data in ascending, descending, or custom order. Learn Bubble, Selection, Insertion, Merge, Quick, Heap, Counting, and Radix Sort to understand algorithm behavior, time complexity, memory use, and interview concepts.

This guide explains common sorting algorithms in C++, their time complexities, stability, memory use, and when to choose each approach.

What Is Sorting in C++?

Sorting in C++ organizes elements into a clear sequence, such as ascending or descending order. This core programming operation makes searching and processing your information much more efficient.

  • Production applications generally rely on highly optimized Standard Template Library tools like std::sort() and std::stable_sort()
  • Calling std::sort() arranges your items in non-descending order by default
  • Adding a custom comparator allows you to define exact sorting rules

Note that std::sort() might shuffle equivalent elements out of their original sequence.

AI-Powered Full Stack Developer ProgramExplore Program
Get the Coding Skills You Need to Succeed

Types of Sorting Algorithms

Sorting algorithms are divided into two primary categories based on their internal operation.

Comparison-based algorithms determine the correct sequence by directly comparing elements. Common examples include Bubble Sort, Selection Sort, Insertion Sort, Merge Sort, Quick Sort, Heap Sort, and STL sort().

Non-comparison-based algorithms organize data by processing the specific digits or frequencies of the underlying values. Counting Sort and Radix Sort are examples of this specialized category.

Sorting Types Diagram

1. Bubble Sort in C++

Bubble Sort is a beginner-friendly algorithm. It traverses the list, compares adjacent elements, and swaps them if they are out of order. This approach makes logical sense for newcomers but yields poor performance on large datasets.

  • The time complexity is O(n²)
  • The space complexity is O(1)
  • You can maintain algorithm stability by swapping adjacent elements strictly when required
#include <vector>
#include <algorithm>
using namespace std;
void bubbleSort(vector<int>& arr) {
    int n = arr.size();
    for (int i = 0; i < n - 1; i++) {
        for (int j = 0; j < n - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                swap(arr[j], arr[j + 1]);
            }
        }
    }
}

2. Selection Sort in C++

Selection Sort works by finding the smallest item in the unsorted section and moving it to the beginning. The logic yields a simple code implementation, but it remains highly inefficient for large inputs, even though it performs fewer swaps than Bubble Sort.

  • The time complexity is O(n²)
  • The space complexity is O(1)
  • Selection Sort behaves unstably unless you specifically modify the underlying implementation
#include <vector>
#include <algorithm>
using namespace std;
void selectionSort(vector<int>& arr) {
    int n = arr.size();
    for (int i = 0; i < n - 1; i++) {
        int minIndex = i;
        for (int j = i + 1; j < n; j++) {
            if (arr[j] < arr[minIndex]) {
                minIndex = j;
            }
        }
        swap(arr[i], arr[minIndex]);
    }
}

3. Insertion Sort in C++

Insertion Sort processes the data sequentially, building the final sorted output one piece at a time. It checks each new item against the sorted group and inserts it into the correct position. 

  • It runs very efficiently for small or nearly sorted arrays
  • The best-case time complexity is O(n) for nearly sorted data
  • The average and worst-case time complexity degrade to O(n²)
  • The space complexity uses O(1)
  • This algorithm remains stable
#include <vector>
using namespace std;
void insertionSort(vector<int>& arr) {
    for (int i = 1; i < arr.size(); i++) {
        int key = arr[i];
        int j = i - 1;
        while (j >= 0 && arr[j] > key) {
            arr[j + 1] = arr[j];
            j--;
        }
        arr[j + 1] = key;
    }
}

4. Merge Sort in C++

Merge Sort applies a divide-and-conquer strategy to handle data. The function splits the target array in half and recursively sorts each half before carefully merging them into a single ordered list.

  • This approach guarantees a predictable time complexity of O(n log n)
  • The process does require extra memory space equal to O(n) complexity
  • You will find it highly useful when stable sorting is required
  • It also works perfectly for sorting linked lists and handling external sorting scenarios
#include <vector>
using namespace std;
void merge(vector<int>& arr, int left, int mid, int right) {
    vector<int> temp;
    int i = left, j = mid + 1;
    while (i <= mid && j <= right) {
        if (arr[i] <= arr[j]) temp.push_back(arr[i++]);
        else temp.push_back(arr[j++]);
    }
    while (i <= mid) temp.push_back(arr[i++]);
    while (j <= right) temp.push_back(arr[j++]);
    for (int k = 0; k < temp.size(); k++) {
        arr[left + k] = temp[k];
    }
}
void mergeSort(vector<int>& arr, int left, int right) {
    if (left >= right) return;
    int mid = left + (right - left) / 2;
    mergeSort(arr, left, mid);
    mergeSort(arr, mid + 1, right);
    merge(arr, left, mid, right);
}

5. Quick Sort in C++

Quick Sort is another popular divide-and-conquer technique. The algorithm picks a central pivot and organizes all other values around that specific point. The algorithm then recursively sorts the resulting partitions. 

  • It delivers fast average performance in practice
  • The expected time complexity is usually O(n log n)
  • Space complexity averages O(log n) due to the recursion stack
  • It behaves unstably by default

Understanding Quick Sort remains essential for handling sorting interview questions.

#include <vector>
#include <algorithm>
using namespace std;
int partition(vector<int>& arr, int low, int high) {
    int pivot = arr[high];
    int i = low - 1;
    for (int j = low; j < high; j++) {
        if (arr[j] < pivot) {
            swap(arr[++i], arr[j]);
        }
    }
    swap(arr[i + 1], arr[high]);
    return i + 1;
}
void quickSort(vector<int>& arr, int low, int high) {
    if (low >= high) return;
    int p = partition(arr, low, high);
    quickSort(arr, low, p - 1);
    quickSort(arr, p + 1, high);
}

6. Heap Sort in C++

Heap Sort organizes data by leveraging a binary heap structure. The algorithm starts by converting the provided input into a structured heap. It then repeatedly extracts the maximum or minimum element and inserts it into the sorted order. Many built-in C++ sorting algorithms actually use Heap Sort internally for hybrid tasks.

  • This method ensures a guaranteed time complexity of O(n log n)
  • The space complexity is O(1) for in-place operations
  • This approach behaves unstably by default
  • It provides predictable worst-case performance while using minimal extra memory
#include <vector>
#include <algorithm>
using namespace std;

void heapSort(vector<int>& arr) {
    make_heap(arr.begin(), arr.end());
    sort_heap(arr.begin(), arr.end());
}

The make_heap function builds the initial heap structure. The sort_heap function subsequently sorts that newly created heap.

7. Counting Sort and Radix Sort in C++

Counting Sort and Radix Sort provide non-comparison options for specific input types. Counting Sort tallies the frequencies of integer values. It works exceptionally well when the value range remains small.

  • The time complexity is O(n + k), where k is the range of values
  • The space complexity is approximately O(k)
  •  Implementing it carefully ensures stability
#include <vector>
using namespace std;
void countingSort(vector<int>& arr, int maxVal) {
    vector<int> count(maxVal + 1, 0);
    for (int x : arr) count[x]++;
    int index = 0;
    for (int value = 0; value <= maxVal; value++) {
        while (count[value]-- > 0) {
            arr[index++] = value;
        }
    }
}

Radix Sort processes numbers digit by digit. It often uses Counting Sort as a fundamental subroutine. You will find it useful for sorting integers or fixed-length strings. 

  • The time complexity is usually measured as O(d × (n + k)), where d denotes the number of digits or passes. 

8. Sorting Using STL sort() in C++

Sorting with STL functions requires including the algorithm header. Learning how to use sort() in C++ provides immediate benefits. 

  • You will call the function by passing the beginning and ending iterators
  • It operates natively on random access iterators
  • This means it works seamlessly when sorting vectors in C++

The default order outputs non-descending sequences. However, passing a greater or a custom lambda function achieves descending order. Writing a custom comparator in C++ is immensely helpful for organizing complex objects or paired data structures. 

  • The STL sort function consistently guarantees O(n log n) comparison steps
  • The function might alter the relative order of items that share the same value

Many developers ask which algorithm std::sort uses. Common implementations typically use Introsort in C++. 

#include <algorithm>
#include <vector>
using namespace std;
struct Item { int first, second; };
struct Record { int score; };
void stlExamples(vector<int>& arr, vector<Item>& items, vector<Record>& records) {
    sort(arr.begin(), arr.end());                 
    sort(arr.begin(), arr.end(), greater<int>()); 

    sort(items.begin(), items.end(), [](auto& a, auto& b) {
       return a.second < b.second;
    });
    stable_sort(records.begin(), records.end(), [](auto& a, auto& b) {
       return a.score < b.score;
    });
}

Which Sorting Algorithm Should You Use?

Developers exploring competitive programming sorting techniques often rely heavily on library functions over manual code. Many programmers search for sorting algorithms in cpp to optimize their applications. Choosing the best sorting algorithm in C++ depends entirely on your business or use case’s data and constraints. 

  • You must consider the time complexity of sorting algorithms as well as their memory usage
  • Understanding stable vs unstable sorting also remains critical here
  • You should also evaluate Quick Sort vs Merge Sort for recursive implementations
  • Determining whether to use stable_sort() or sort() is a common decision point depending on your stability needs
Learn 45+ in-demand full-stack development skills and tools, including Frontend Development, Backend Development, Version Control and Collaboration, Database Management, and AI Assisted Development, with our AI-Powered Full Stack Developer Course.

Key Takeaways

  • Sorting in C++ helps prepare your data for simpler searching and further processing
  • Basic algorithms like Bubble Sort, Selection Sort, and Insertion Sort work well for learning basic logic, but they struggle with large inputs
  • Merge Sort delivers stable and predictable output at the cost of additional memory space
  • Quick Sort operates fast on average, but worst cases cause extreme performance drops
  • Real C++ programs generally rely on std::sort() as the safest default choice
Want the flexibility to build complete applications from end to end? Explore the skills, technologies, salary potential, and career growth opportunities for Full Stack Developers with this Full-Stack Developer Roadmap.

FAQs

1. Which sorting algorithm is best in C++?

For most C++ programs, std::sort() remains the best default choice. It is highly optimized and guarantees O(n log n) performance. Use std::stable_sort() for ordered equal elements.

2. What is STL sort() in C++?

STL sort() is a standard library function that sorts elements. It operates on random-access iterators and handles vectors seamlessly with an optional custom comparator.

3. What is the difference between Merge Sort and Quick Sort?

Merge Sort partitions data in half to achieve stable O(n log n) execution. Quick Sort partitions around a pivot, yielding fast average speeds, but lacks guaranteed stability.

4. What is Heap Sort in C++?

Heap Sort provides an efficient, comparison-based approach by maintaining a binary heap structure. The process repeatedly pulls the maximum value to finish within a guaranteed O(n log n) time frame.

5. When should I use Merge Sort instead of Quick Sort?

Choose Merge Sort whenever absolute sorting stability and predictable worst-case performance matter most. It works exceptionally well for sorting linked lists and external database files.

About the Author

Ravikiran A SRavikiran A S

Ravikiran A S is a Technical Content Strategist and Data Analyst. He an enthusiastic geek always in the hunt to learn the latest technologies. He is proficient with Java Programming Language, Big Data, and powerful Big Data Frameworks like Apache Hadoop and Apache Spark.

View More
  • Acknowledgement
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, OPM3 and the PMI ATP seal are the registered marks of the Project Management Institute, Inc.
  • *All trademarks are the property of their respective owners and their inclusion does not imply endorsement or affiliation.
  • Career Impact Results vary based on experience and numerous factors.