A Guide to Sort Function in C++

A Guide to Sort Function in C++

3 mins read71 Views Comment
Esha
Esha Gupta
Associate Senior Executive
Updated on Mar 20, 2024 17:53 IST

Have you ever wondered how to organize data in C++ efficiently? The sort function in C++ comes to the rescue, offering a powerful and straightforward way to arrange elements in a sequence into a specified order. This function is part of the Standard Template Library (STL) and can be customized to sort arrays or vectors according to specific criteria, enhancing the performance and readability of your code. Let's understand more!

2023_09_What-is-13-1.jpg

The Sort Function in C++ is a utility function provided by the C++ Standard Library to arrange elements in a range (like arrays or vectors) in a sorted order, either in ascending or descending order, based on specified criteria.

How is it useful?

  • With just a single line of code, you can sort an entire collection of elements, which helps to keep your code concise and readable.
  • Allows for easy customization through comparators, so you can define complex sorting criteria without making the code overly complex.
  • The std::sort function is highly optimized, generally offering very good performance characteristics. It performs better than straightforward implementations of common sorting algorithms like bubble or insertion sort.
  • The std::sort function integrates well with other parts of the C++ Standard Template Library (STL), allowing for powerful combinations of algorithms and data structures.

The Sort Function in C++ typically uses an efficient sorting algorithm called introsort, a hybrid sorting algorithm. Introsort combines quicksort, heapsort, and insertion sort elements to achieve good average-case and worst-case time complexity while maintaining performance across different scenarios.

By default, the sort function will sort the elements in ascending order.

Recommended online courses

Best-suited C++ courses for you

Learn C++ with these high-rated online courses

– / –
4 months
β‚Ή4.24 K
6 weeks
– / –
15 days
– / –
– / –
– / –
70 hours
– / –
3 months
– / –
1 hours
Free
2 hours
Free
1 hours
Free
1 hours

Examples to Understand Sort Function in C++

Introduction to QuickSort Algorithm in C++
Introduction to QuickSort Algorithm in C++
The Quicksort algorithm in C++ is an efficient sorting technique that uses a divide-and-conquer approach. It works by selecting a 'pivot' element, partitioning the array into two sub-arrays around the...read more
Insertion Sort in C++
Insertion Sort in C++
In this tutorial, we are going to learn about one of the most common and simplest sorting techniques – insertion sort, and we are going to see how this technique...read more
Merge Sort Algorithm (With Code)
Merge Sort Algorithm (With Code)
Merge Sort Algorithm is one of the sorting algorithm similar to selection sort, insertion sort, quick sort algorithms. In this article, we will briefly discuss merge sort algorithm and its...read more

Sorting in Ascending Order


 
#include <iostream>
#include <algorithm> // Include the necessary header
int main() {
int arr[] = {5, 4, 2, 1, 3};
int n = sizeof(arr) / sizeof(arr[0]);
// Using std::sort to sort the array in ascending order
std::sort(arr, arr + n);
std::cout << "Sorted Array in Ascending Order: ";
for (int i = 0; i < n; i++) {
std::cout << arr[i] << " ";
}
return 0;
}
Copy code

Output

Sorted Array in Ascending Order: 1 2 3 4 5 

This demonstrates the default behaviour of std::sort() in C++, sorting elements in ascending order.

 

Sorting in Descending Order

Binary Search in C++
Binary Search in C++
This article is talking about binary search in iterative and recursive way using C++. This article is talking about binary search in iterative and recursive way using C++.This article is...read more
Bubble Sort Algorithm (With Code)
Bubble Sort Algorithm (With Code)
In today’s world of continuous data generation, it is of utmost importance for all businesses to sort data linearly and attain relationships on the same. With different types of sorting...read more
Selection Sort Algorithm in C
Selection Sort Algorithm in C
Ever wondered how your favorite music app arranges songs from least to most played, or how an online store lists products from cheapest to priciest? At the heart of such...read more

 
#include <iostream>
#include <algorithm>
#include <vector>
int main() {
std::vector<int> vec = {1, 5, 2, 4, 3};
// Using std::sort to sort the vector in descending order
std::sort(vec.begin(), vec.end(), std::greater<int>());
std::cout << "Sorted Vector in Descending Order: ";
for (int i : vec) {
std::cout << i << " ";
}
return 0;
}
Copy code

Output

Sorted Vector in Descending Order: 5 4 3 2 1 

This demonstrates how to use std::greater<>() to sort elements in descending order with the std::sort() function in C++.

Sorting, in Particular Order


 
#include <iostream>
#include <algorithm>
#include <vector>
// Custom comparator function
bool customComparator(const std::string& name1, const std::string& name2) {
// Sort names alphabetically in ascending order
return name1 < name2;
}
int main() {
std::vector<std::string> names = {"Esha", "Hrithik", "Hroohee", "Hrahe", "Ehsas"};
// Using std::sort with the customComparator to sort names alphabetically in ascending order
std::sort(names.begin(), names.end(), customComparator);
std::cout << "Sorted Names (Ascending Order): ";
for (const std::string& name : names) {
std::cout << name << " ";
}
return 0;
}
Copy code

Output

Sorted Names (Ascending Order): Ehsas Esha Hrahe Hrithik Hroohee

You can define custom comparators to sort elements based on any specific criteria you need, such as alphabetical order, length, or any other custom comparison logic.

Miscellaneous Example of Sort Function in C++

In this example, we’ll create a vector of Person objects and sort them based on their ages:


 
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
// Define a custom class for Person
class Person {
public:
std::string name;
int age;
// Constructor
Person(const std::string& n, int a) : name(n), age(a) {}
// Overload the less-than operator for custom comparison
bool operator<(const Person& other) const {
return age < other.age;
}
};
int main() {
// Create a vector of Person objects
std::vector<Person> people = {
{"Esha", 30},
{"Hrithik", 19},
{"Isha", 7},
{"Gauri", 10},
{"Ishani", 34}
};
// Sort the vector of Person objects based on age
std::sort(people.begin(), people.end());
// Print the sorted list of people
std::cout << "Sorted People by Age:\n";
for (const Person& person : people) {
std::cout << "Name: " << person.name << ", Age: " << person.age << "\n";
}
return 0;
}
Copy code

Output

Sorted People by Age:
Name: Isha, Age: 7
Name: Gauri, Age: 10
Name: Hrithik, Age: 19
Name: Esha, Age: 30
Name: Ishani, Age: 34

Thus, the std::sort function in C++ is a powerful tool for sorting elements in various data structures like arrays, vectors, and other containers.

FAQs

What is the sort function in C++?

The sort function in C++ is a standard library function that arranges the elements of a container (like an array or vector) in a specified order. It's part of the Standard Template Library (STL).

How do you use the sort function on an array?

To sort an array, you would include the <algorithm> header and use the sort function specifying the start and end pointers of the array: sort(arr, arr + n); where n is the number of elements in the array.

Can the sort function sort in descending order?

Yes, the sort function can sort elements in descending order by providing a third parameter as a comparison function or using the greater<int>() predefined function: sort(arr, arr + n, greater<int>());

Is it possible to sort a part of an array using the sort function?

es, you can sort a part of an array by specifying the starting and ending pointers of the subrange you want to sort: sort(arr + start, arr + end + 1);

How does the sort function compare elements by default?

By default, the sort function compares elements using the < operator, meaning it will arrange elements in ascending order based on their natural ordering.

About the Author
author-image
Esha Gupta
Associate Senior Executive

Hello, world! I'm Esha Gupta, your go-to Technical Content Developer focusing on Java, Data Structures and Algorithms, and Front End Development. Alongside these specialities, I have a zest for immersing myself in v... Read Full Bio