0
0
CppHow-ToBeginner · 3 min read

How to Sort Array in C++: Syntax and Examples

To sort an array in C++, use the std::sort function from the <algorithm> header. Call std::sort(array, array + size) where array is your array and size is its length to sort it in ascending order.
📐

Syntax

The basic syntax to sort an array in C++ is:

  • std::sort(start, end); where start is a pointer or iterator to the first element.
  • end is a pointer or iterator just past the last element.
  • This sorts the elements in ascending order by default.
cpp
std::sort(array, array + size);
💻

Example

This example shows how to sort an integer array in ascending order using std::sort. It prints the array before and after sorting.

cpp
#include <iostream>
#include <algorithm>

int main() {
    int arr[] = {5, 2, 9, 1, 5, 6};
    int size = sizeof(arr) / sizeof(arr[0]);

    std::cout << "Before sorting: ";
    for (int i = 0; i < size; ++i) {
        std::cout << arr[i] << " ";
    }
    std::cout << "\n";

    std::sort(arr, arr + size);

    std::cout << "After sorting: ";
    for (int i = 0; i < size; ++i) {
        std::cout << arr[i] << " ";
    }
    std::cout << "\n";

    return 0;
}
Output
Before sorting: 5 2 9 1 5 6 After sorting: 1 2 5 5 6 9
⚠️

Common Pitfalls

Common mistakes when sorting arrays in C++ include:

  • Not including the <algorithm> header, which causes a compile error.
  • Passing incorrect pointers or iterators, such as array and array + size - 1 instead of array + size. The end pointer must be one past the last element.
  • Trying to sort arrays of non-comparable types without a custom comparator.
cpp
#include <algorithm>

int arr[5] = {3, 1, 4, 1, 5};
// Wrong: end pointer is array + size - 1, misses last element
// std::sort(arr, arr + 4); // sorts only first 4 elements

// Correct:
std::sort(arr, arr + 5);
📊

Quick Reference

Summary tips for sorting arrays in C++:

  • Include <algorithm> to use std::sort.
  • Use std::sort(array, array + size); to sort in ascending order.
  • For descending order, use a custom comparator like std::greater<int>().
  • Works with built-in arrays and containers like std::vector.

Key Takeaways

Use std::sort from to sort arrays in C++.
Pass the array start pointer and one past the last element as arguments.
Remember to include header to avoid errors.
Use custom comparators for descending or custom order sorting.
Check array size carefully to include all elements in sorting.