A Guide to Sort Function in C++

A Guide to Sort Function in C++

2 mins read69 Views Comment
clickHere
Esha
Esha Gupta
Associate Senior Executive
Updated on Oct 16, 2023 11:34 IST

Have you ever wanted to bring order to chaos, just like how the sort function in C++ effortlessly arranges elements in a sequence? Let us 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.

Examples to Understand Sort Function in C++

Introduction to QuickSort Algorithm in C++
Introduction to QuickSort Algorithm in C++
In this tutorial, we are going to learn about a common sorting technique – QuickSort, and we are going to see how this technique is implemented in C++.
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++.
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...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

Conclusion

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

Download this article as PDF to read offline

Download as PDF
clickHere
About the Author
author-image
Esha Gupta
Associate Senior Executive

I'm Esha Gupta, a B.Tech graduate in Computer Science & Engineering, specializing in Front End Web Dev. I've interned at GeeksforGeeks & Coding Minutes, fueling my passion for crafting appealing and functional digit... Read Full Bio

Comments

We use cookies to improve your experience. By continuing to browse the site, you agree to our Privacy Policy and Cookie Policy.