Open In App

Sort in C++ Standard Template Library (STL)

Last Updated : 11 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Sorting is one of the most basic operations applied to data. It means arranging the data in a particular order, which can be increasing, decreasing or any other order. In this article, we will discuss various ways of sorting in C++.

C++ provides a built-in function in C++ STL called sort() as the part of <algorithm> library for sorting the containers such as arrays, vectors, deque, etc.

sort(first, last, comp);

where,

  • first: The beginning of the range to be sorted.
  • last: The end of the range to be sorted.
  • comp (optional): A custom comparison function to define sorting order. By default, it is ascending order.

Let's take a look at an example that sorts the given vector in ascending order:

C++
#include <bits/stdc++.h>
using namespace std;

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

    // Default ascending order
    sort(v.begin(), v.end());

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

Output
1 2 3 4 5 

The sort() function implements the introsort sorting algorithm which is a combination of insertion sort, quick sort and heap sort. It automatically determines which algorithm to use according to the dataset.

Sorting data is a common operation in programming.

Other Sorting Algorithms in C++

Unfortunately, C++ does not provide implementation of any other sorting algorithm than Introsort and we can also not instruct to execute a particular algorithm to sort method. So, if we need a different sorting algorithm such as counting sort, we have to implement it by ourselves.

Bubble Sort Algorithm

Bubble Sort is a comparison-based sorting algorithm. It works by repeatedly swapping adjacent elements if they are in the wrong order, placing one element to its correct position in each iteration. Let's take a look at its implementation:

C++
#include <bits/stdc++.h>
using namespace std;

// Implementation of bubble sort algorithm
void bubbleSort(vector<int>& v) {
    int n = v.size();
    for (int i = 0; i < n - 1; i++) {
        for (int j = 0; j < n - i - 1; j++) {
            if (v[j] > v[j + 1]) {
              
                // Swap element if in wrong order
                swap(v[j], v[j + 1]);
            }
        }
    }
}

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

    // Use Bubble Sort to sort vector v
    bubbleSort(v);

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

Output
1 2 3 4 5 

Counting Sort Algorithm

Counting Sort is a non-comparison-based sorting algorithm. It works by counting the frequency of each distinct element in the input and use that information to place the elements in their correct sorted positions. Let's take a look at its implementation:

C++
#include <bits/stdc++.h>
using namespace std;

// Implementation of counting sort algorithm
void countingSort(vector<int>& v) {
    int m = *max_element(v.begin(), v.end());
    vector<int> count(m + 1, 0);
    for (int i : v) {
        count[i]++;
    }

    int index = 0;
    for (int i = 0; i <= m; i++) {
        while (count[i] > 0) {
            v[index++] = i;
            count[i]--;
        }
    }
}

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

    // Use Counting Sort to sort vector v
    countingSort(v);

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

Output
1 2 3 4 5 

In a similar way, we can implement any sorting algorithm of our choice and need.

Common Sorting Problems in C++

As told earlier, sorting is one of the frequently used operations on data. It is used in solving a lot of programming problems. The below examples demonstrate the use of sort() in different problems:

Remove Duplicates in a Vector

C++
#include <bits/stdc++.h>
using namespace std;

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

  	// Sort the vector to bring duplicate elements adjacent
    sort(v.begin(), v.end());

    // Use unique() to bring all the duplicates to end
    auto it = unique(v.begin(), v.end());

    // Remove the duplicates
    v.erase(it, v.end());

    for (auto& i : v) cout << i << " ";
    return 0;
}

Output
1 2 3 4 5 

Find the Kth Largest Element in an Array

C++
#include <bits/stdc++.h>
using namespace std;

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

  	// Sort the vector
    sort(arr, arr + n);

    // 3rd largest element will be present at 3 - 1 index
	cout << arr[k - 1];
  
    return 0;
}

Output
3

Find the Pair with the Minimum Difference

C++
#include <bits/stdc++.h>
using namespace std;

pair<int, int> findMinDiff(vector<int>& v) {
    
    // Sort the vector
    sort(v.begin(), v.end());

    // Initialize variables to track the minimum difference and the pair
    int minDiff = INT_MAX;
    pair<int, int> res;

    // Traverse the vector to find the minimum difference
    for (auto i = 0; i < v.size() - 1; i++) {
        int diff = v[i + 1] - v[i];
        if (diff < minDiff) {
            minDiff = diff;
            res = {v[i], v[i + 1]};
        }
    }

    return res;
}

int main() {
    vector<int> v = {4, 2, 9, 7, 1, 5};

    // Find the pair with the minimum difference
    pair<int, int> res = findMinDiff(v);

    cout << res.first << ", " << res.second;
    return 0;
}

Output
1, 2

Next Article
Article Tags :
Practice Tags :

Similar Reads

  翻译: