sort() in C++ STL (original) (raw)

Last Updated : 23 May, 2026

The sort() function is used to sort elements in a container or array. It provides a simple and efficient way to sort data in C++.

#include using namespace std;

int main(){ vector v = {5, 3, 2, 1, 4};

// Sort vector (by default in ascending order)
sort(v.begin(), v.end());

for (int i : v)
    cout << i << " ";
return 0;

}

`

Syntax

The std::sort() function is defined inside the header file.

sort(first, last);

**Parameters

Variations and Usage of sort() in C++ STL

1. Sort the entire range (default ascending order)

C++ `

#include #include using namespace std;

int main(){ int arr[5] = {5, 3, 2, 1, 4}; int n = sizeof(arr) / sizeof(arr[0]);

// Sort array (by default in ascending order)
sort(arr, arr + n);

for (int i : arr)
    cout << i << " ";
return 0;

}

`

2. Sort a specific range

C++ `

#include #include using namespace std;

int main(){ int arr[] = {10, 5, 8, 1, 7, 3}; int n = sizeof(arr) / sizeof(arr[0]);

sort(arr + 1, arr + 5);
for (int i = 0; i < n; i++)
    cout << arr[i] << " ";

return 0;

}

`

**Explanation: sort(arr + 1, arr + 5); sorts the array elements from index 1 to 4 while leaving the rest unchanged.

3. Sort Array in Descending Order

C++ `

#include #include using namespace std;

int main() { int arr[5] = {5, 3, 2, 1, 4}; int n = sizeof(arr) / sizeof(arr[0]);

// Sort array in descending order
sort(arr, arr + n, greater<int>());

for (int i : arr)
    cout << i << " ";

return 0;

}

`

**Explanation: sort(arr, arr + n, greater()); sorts the entire array in descending order.

4. Sort Vector of User Defined Type

C++ `

#include #include #include using namespace std;

struct Point{ int x; int y; };

int main(){ vector points = {{3, 5}, {1, 2}, {4, 1}};

// Sort points by x value (ascending)
sort(points.begin(), points.end(), [](const Point &a, const Point &b) 
{ return a.x < b.x; });

for (auto p : points)
    cout << "(" << p.x << "," << p.y << ") ";

return 0;

}

`

Try It Yourselfredirect icon

**Explanation

Working of sort() Function

The sort() function is implemented using the Introsort (Intro Sort) algorithm, which is a hybrid sorting technique.

Step-by-step working:

  1. Start with Quick Sort: The algorithm initially uses Quick Sort because it is fast and efficient for average cases.
  2. Monitor Recursion Depth: While performing Quick Sort, the algorithm keeps track of the recursion depth to avoid worst-case performance.
  3. Switch to Heap Sort if Needed: If the recursion depth exceeds a certain limit, it switches to Heap Sort to guarantee O(n log n) performance.
  4. Use Insertion Sort for Small Arrays: For very small subarrays, Insertion Sort is used as it performs better on small data sets.
  5. Final Sorted Output: By combining these techniques, sort() ensures both high performance and worst-case safety.