Table of contents
1.
Introduction
2.
Algorithm
3.
Sorting a Vector in C++ in Ascending Order
4.
Sorting a Vector in C++ in Descending Order :
5.
How to sort the array in descending order based on some parameter using a comparator function?
6.
Frequently Asked Questions
6.1.
Can I sort a vector of custom objects in C++?
6.2.
Is it possible to sort a vector in ascending order without using the std::sort() function?
6.3.
How can I sort a vector in descending order based on multiple parameters?
7.
Conclusion
Last Updated: Oct 18, 2024
Easy

Sorting a Vector in C++

Author Ravi Khorwal
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Sorting data is a fundamental task in computer programming. In C++, vectors are a convenient way to store & manipulate collections of elements. Sorting vectors allows you to arrange the elements in a specific order, which can be useful for various tasks like searching, analyzing data, or presenting information in a meaningful way. Sorting these vectors can be crucial for optimizing searches or order-dependent algorithms. 

Sorting a Vector in C++

In this article, we'll learn how to sort vectors in C++ using different algorithms & techniques. We'll cover sorting in both ascending & descending order, as well as using custom comparator functions to sort based on specific criteria. 

Algorithm

The C++ standard library provides a built-in sort() function that is specifically designed to sort vectors & other containers. The sort() function is defined in the <algorithm> header & uses a hybrid sorting algorithm known as introsort.

Introsort is a combination of three sorting algorithms:

 

1. Quick Sort: This is the main sorting algorithm used by introsort. It partitions the vector into two sub-vectors based on a pivot element & recursively sorts the sub-vectors.
 

2. Heap Sort: If the recursive depth of quick sort exceeds a certain threshold (typically 2 * log(n), where n is the number of elements), introsort switches to heap sort. Heap sort is a comparison-based sorting algorithm that uses a binary heap data structure to sort the elements.
 

3. Insertion Sort: For small sub-vectors (typically fewer than 16 elements), introsort switches to insertion sort, which is more efficient for small input sizes.


The introsort algorithm intelligently chooses between these three sorting algorithms based on the input size & the recursive depth to provide the best average-case performance. It has a time complexity of O(n * log(n)) in the average & best cases, & a space complexity of O(log(n)) due to the recursive calls.


Let’s discuss how the sort() function works when applied to a vector:
 

1. If the vector has fewer than 16 elements, apply insertion sort & return.
 

2. Choose a pivot element from the vector (usually the middle element).
 

3. Partition the vector into two sub-vectors based on the pivot: elements less than the pivot & elements greater than the pivot.
 

4. Recursively apply the sorting algorithm to the sub-vectors.
 

5. If the recursive depth exceeds 2 * log(n), switch to heap sort for the remaining unsorted sub-vectors.
 

6. Combine the sorted sub-vectors to obtain the final sorted vector.


For example : 

#include <algorithm>
#include <iostream>
#include <vector>

int main() {
    std::vector<int> numbers = {5, 2, 8, 12, 1};


    std::cout << "Before sorting: ";
    for (int num : numbers) {
        std::cout << num << " ";
    }
    std::cout << std::endl;

    std::sort(numbers.begin(), numbers.end());

    std::cout << "After sorting: ";
    for (int num : numbers) {
        std::cout << num << " ";
    }
    std::cout << std::endl;

    return 0;
}
You can also try this code with Online C++ Compiler
Run Code


Output:

Before sorting: 5 2 8 12 1
After sorting: 1 2 5 8 12


In this example, we create a vector named numbers and initialize it with some integer values. We print the contents of the vector before sorting using a range-based for loop. Then, we use std::sort() and pass the begin() and end() iterators of the vector to sort it in ascending order. Finally, we print the contents of the vector after sorting to verify that it is now in ascending order.

Note: The sort() function in C++ is highly optimized & provides a fast & efficient way to sort vectors. It handles various edge cases & optimizes the sorting process based on the input size, which ensures good performance across different scenarios.

Sorting a Vector in C++ in Ascending Order

To sort a vector in ascending order, you can simply use the std::sort() function from the <algorithm> header. For example:

#include <algorithm>
#include <iostream>
#include <vector>
int main() {
    std::vector<int> numbers = {5, 2, 8, 12, 1};
    std::cout << "Before sorting: ";
    for (int num : numbers) {
        std::cout << num << " ";
    }
    std::cout << std::endl;
    std::sort(numbers.begin(), numbers.end());
    std::cout << "After sorting in ascending order: ";
    for (int num : numbers) {
        std::cout << num << " ";
    }
    std::cout << std::endl;
    return 0;
}
You can also try this code with Online C++ Compiler
Run Code


Output

Before sorting: 5 2 8 12 1
After sorting in ascending order: 1 2 5 8 12


In this example:

1. We create a vector named "numbers" & initialize it with some integer values.
 

2. We print the contents of the vector before sorting using a range-based for loop.
 

3. We use std::sort() & pass the begin() & end() iterators of the vector to sort it in ascending order.
 

4. Finally, we print the contents of the vector after sorting to verify that it is now in ascending order.
 

The std::sort() function uses the < operator by default to compare elements. For built-in types like int, float, double, etc., this results in sorting the elements in ascending order.

You can sort vectors of other types as well, such as strings or custom objects, as long as the type has a valid < operator or a custom comparator function defined.

For example, to sort a vector of strings in ascending order:

std::vector<std::string> words = {"apple", "banana", "cherry", "date"};
std::sort(words.begin(), words.end());
After sorting, the vector "words" will contain: {"apple", "banana", "cherry", "date"}.

Sorting a Vector in C++ in Descending Order :

To sort a vector in descending order, you can use the std::sort() function along with the std::greater<>() comparator from the <functional> header. For example:

#include <algorithm>
#include <functional>
#include <iostream>
#include <vector>
int main() {
    std::vector<int> numbers = {5, 2, 8, 12, 1};
    std::cout << "Before sorting: ";
    for (int num : numbers) {
        std::cout << num << " ";
    }
    std::cout << std::endl;
    std::sort(numbers.begin(), numbers.end(), std::greater<>());
    std::cout << "After sorting in descending order: ";
    for (int num : numbers) {
        std::cout << num << " ";
    }
    std::cout << std::endl;
    return 0;
}
You can also try this code with Online C++ Compiler
Run Code


Output

Before sorting: 5 2 8 12 1
After sorting in descending order: 12 8 5 2 1


In this example:

1. We create a vector named "numbers" & initialize it with some integer values.
 

2. We print the contents of the vector before sorting using a range-based for loop.
 

3. We use std::sort() & pass the begin() & end() iterators of the vector along with std::greater<>() as the comparator function to sort the vector in descending order.
 

4. Finally, we print the contents of the vector after sorting to verify that it is now in descending order.


The std::greater<>() comparator is a predefined function object in C++ that compares two elements using the > operator. By passing std::greater<>() as the third argument to std::sort(), we instruct the sorting algorithm to use the > operator instead of the default < operator, resulting in descending order sorting.

You can use this technique to sort vectors of other types in descending order as well. For example, to sort a vector of strings in descending order:

std::vector<std::string> words = {"apple", "banana", "cherry", "date"};
std::sort(words.begin(), words.end(), std::greater<>());
After sorting, the vector "words" will contain: {"date", "cherry", "banana", "apple"}.

How to sort the array in descending order based on some parameter using a comparator function?

In C++, you can define a custom comparator function to sort a vector based on a specific parameter or criteria. This is particularly useful when you have a vector of custom objects & want to sort them based on a particular attribute or a combination of attributes.

Let’s see an example showing sorting a vector of custom objects in descending order based on a specific parameter:

#include <algorithm>
#include <iostream>
#include <vector>
struct Person {
    std::string name;
    int age;
};
bool compareByAge(const Person& a, const Person& b) {
    return a.age > b.age;
}
int main() {
    std::vector<Person> people = {
        {"Mehak", 25},
        {"Rahul", 30},
        {"Sneha", 20},
        {"Aman", 35}
    };
    std::cout << "Before sorting:\n";
    for (const Person& person : people) {
        std::cout << person.name << " - " << person.age << std::endl;
    }
    std::sort(people.begin(), people.end(), compareByAge);
    std::cout << "\nAfter sorting by age in descending order:\n";
    for (const Person& person : people) {
        std::cout << person.name << " - " << person.age << std::endl;
    }
    return 0;
}
You can also try this code with Online C++ Compiler
Run Code


Output

Before sorting:
Mehak - 25
Rahul - 30
Sneha - 20
Aman - 35
After sorting by age in descending order:
Aman - 35
Rahul - 30
Mehak - 25
Sneha - 20


In this example:

1. We define a custom struct named "Person" with two members: "name" (string) & "age" (int).
 

2. We define a custom comparator function named "compareByAge" that takes two "Person" objects as parameters & compares them based on their "age" member. The function returns true if the age of the first person is greater than the age of the second person, resulting in descending order sorting.
 

3. In the main() function, we create a vector of "Person" objects & initialize it with some sample data.
 

4. We print the contents of the vector before sorting.
 

5. We use std::sort() & pass the begin() & end() iterators of the vector along with the "compareByAge" function as the comparator to sort the vector in descending order based on the "age" parameter.
 

6. Finally, we print the contents of the vector after sorting to verify that it is now sorted in descending order based on the "age" parameter.


Note: You can define custom comparator functions to sort vectors based on any desired criteria. The comparator function should return true if the first element is considered greater than the second element according to the sorting criteria.

Frequently Asked Questions

Can I sort a vector of custom objects in C++?

Yes, you can sort a vector of custom objects in C++ by defining a custom comparator function that specifies the sorting criteria based on the object's attributes.

Is it possible to sort a vector in ascending order without using the std::sort() function?

Yes, you can implement your own sorting algorithm, such as bubble sort or selection sort, to sort a vector in ascending order. However, using std::sort() is recommended as it is highly optimized & efficient.
 

How can I sort a vector in descending order based on multiple parameters?

To sort a vector in descending order based on multiple parameters, you can define a custom comparator function that compares the objects based on the desired parameters in the specified order. The comparator function should return true if the first object is considered greater than the second object according to the sorting criteria.

Conclusion

In this article, we discussed how to sort vectors in C++ using the std::sort() function & custom comparator functions. We learned how to sort vectors in ascending & descending order, as well as how to sort vectors of custom objects based on specific parameters. Sorting vectors is a fundamental operation in C++ that allows you to organize & manipulate data efficiently. 

You can also check out our other blogs on Code360.

Live masterclass