For working professionals
For fresh graduates
More
Explore C++ Tutorials: Explori…
1. The Ultimate C++ Guide: C++ Tutorial for Beginners
2. Application of C++
3. C++ Hello World Program
4. C++ Variable
5. Reference Variable in C++
6. Function Overloading in C++
7. Functions in C++
8. Pointer in C++
9. Data Types in C++
10. C++ for Loop
11. While Loop in C++
12. C++ Lambda
13. Loop in C++
14. Switch Case in C++
15. Array in C++
16. Strings in C++
17. Substring in C++
18. Class and Object in C++
19. Constructor in C++
20. Copy Constructor in C++
21. Destructor in C++
22. Multiple Inheritance in C++
23. Encapsulation in C++
24. Single Inheritance in C++
25. Friend Class in C++
26. Hierarchical Inheritance in C++
27. Virtual Base Class in C++
28. Abstract Class in C++
29. Vector in C++
30. Map in C++
31. Pair in C++
32. Initialize Vector in C++
33. Iterators in C++
34. Queue in C++
35. Priority Queue in C++
36. Stack in C++
37. ifstream in C++
38. Exception Handling in C++
39. Memory Management in C++
40. Templates in C++
41. Type Conversion in C++
42. Enumeration in C++
43. Namespace in C++
44. Set Precision in C++
45. Stringstream in C++
46. Recursion in C++
47. Random Number Generator in C++
48. C++ Shell
49. Setw in C++
50. Multithreading in C++
51. Atoi in C++
52. Call by Value and Call by Reference in C++
53. Difference Between C and C++
54. C# vs C++
55. C++ GUI
56. C++ Game Code
57. Class in C++
58. C++ Header Files
59. Power Function in C++
60. Data Hiding in C++
61. Inline Function in C++
62. Getline Function in C++
63. Cin in C++
64. Printf in C++
65. Struct in C++
66. C++ List
67. static_cast in C++
68. C++ Comments
69. Structures in C++
70. C++ Standard Template Library (STL)
71. Virtual Function in C++
72. Sorting in C++
Now Reading
73. Polymorphism in C++
74. Oops Concepts in C++
75. Converting Integers to Strings in C++
76. Differences Between Break and Continue
Sorting methods are very important to make data processing better and to help C++ programs run faster. In this article, I will explain in detail about sorting in C++, cover the different kinds of sorts, how they work, and the special points about each method. If you are just starting or already have programming experience, knowing these ideas is very important to make programs that work well and solve problems correctly. We will start learning how to do sorting in C++ together.
Putting sorting into practice in C++ might feel overwhelming initially, but once you find the correct method, it gets simple. C++ comes with a strong standard template library that has functions for sorting which helps programmers such as myself to organize data with ease. I frequently use the std::sort function, which is in the <algorithm> header, to arrange arrays and containers in order.
Here’s a simple example of how I implement sorting on an array of integers:
Example:
#include <iostream>#include <algorithm>int main() { int arr[] = {5, 2, 9, 1, 5, 6}; std::sort(arr, arr + 6); for (int i = 0; i < 6; i++) { std::cout << arr[i] << " "; } return 0;}
Output:
1 2 5 5 6 9
In this example, std::sort is used to sort the array in ascending order. You can customize the sorting order by providing a third parameter, a binary predicate that determines the sorting criteria.
C++ allows me to use different sorting algorithms. There are many kinds, each one with its own features and situations where it is useful. Here are some of the most common sorting algorithms I use in C++:
When I must arrange an array in C++, my first choice is to use the std::sort function. But if I require extra control or want to put in place my own method for sorting, then a particular sorting algorithm might be selected by me. Here’s how I might implement an algorithm of quick sort:
Algorithm:
void quickSort(int arr[], int low, int high) {
if (low < high) {
int pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
This algorithm helps recursively sort the elements of the array using the Quick Sort algorithm.
A stable sort preserves the relative order of records with equal keys or values. In other words, if two elements are equal, they will remain in the same order as they were in the input, after the sorting is complete. This property is significant when I sort data that has multiple fields.
For instance, consider I have a list of students sorted by name and I want to sort them by their grade. A stable sorting algorithm will ensure that students with the same grade will remain in the same order they were originally, relative to each other.
Here is an example in C++ using std::stable_sort:
Example:
#include <iostream>
#include <vector>
#include <algorithm>
struct Student {
std::string name;
int grade;
};
// Comparator function for sorting by grade
bool compareByGrade(const Student& a, const Student& b) {
return a.grade < b.grade;
}
int main() {
std::vector<Student> students = {
{"Alice", 90}, {"Bob", 75}, {"Charlie", 90}, {"Dave", 75}
};
// Using stable_sort to sort by grade
std::stable_sort(students.begin(), students.end(), compareByGrade);
for (const auto& student : students) {
std::cout << student.name << " " << student.grade << "\n";
}
return 0;
}
Output:
Bob 75
Dace 75
Alice 90
Charlie 90
Notice how Bob and Dave, as well as Alice and Charlie, maintain their relative order post sorting.
An unstable sort does not guarantee to preserve the order of equal elements. This means that two equal elements might appear in a different order in the sorted output compared to the input. Unstable sorting can be more efficient in terms of time and space because it doesn't require the extra effort to maintain the order of equal elements.
Here’s how sorting behaves unstably using std::sort:
Example:
#include <iostream>
#include <vector>
#include <algorithm>
struct Student {
std::string name;
int grade;
};
// Comparator function for sorting by grade
bool compareByGrade(const Student& a, const Student& b) {
return a.grade < b.grade;
}
int main() {
std::vector<Student> students = {
{"Alice", 90}, {"Bob", 75}, {"Charlie", 90}, {"Dave", 75}
};
// Using sort (potentially unstable) to sort by grade
std::sort(students.begin(), students.end(), compareByGrade);
for (const auto& student : students) {
std::cout << student.name << " " << student.grade << "\n";
}
return 0;
}
Output:
Bob 75
Dace 75
Alice 90
Charlie 90
The order of Bob and Dave, as well as Alice and Charlie, may vary because std::sort does not guarantee stability.
The choice between stable and unstable sorting can impact performance:
Choosing the right sort C++ algorithm depends on the nature of the data and the application. For most standard uses, std::sort suffices, but understanding the underlying algorithms is beneficial for optimizing sorting in specific scenarios. For example, if I'm working with large datasets that are mostly sorted, I might prefer insertion sort due to its adaptive nature.
To implement a complete sorting program in C++, I consider the data structure and the best sorting algorithm for my needs. Here is a simple example of a program that sorts a vector of integers using merge sort:
Example:
#include <vector>
#include <iostream>
void merge(std::vector<int>& left, std::vector<int>& right, std::vector<int>& bars) {
int nL = left.size();
int nR = right.size();
int i = 0, j = 0, k = 0;
while (j < nL && k < nR) {
if (left[j] < right[k]) {
bars[i] = left[j];
j++;
}
else {
bars[i] = right[k];
k++;
}
i++;
}
while (j < nL) {
bars[i] = left[j];
j++; i++;
}
while (k < nR) {
bars[i] = right[k];
k++; i++;
}
}
void mergeSort(std::vector<int>& bar) {
if (bar.size() <= 1) return;
int mid = bar.size() / 2;
std::vector<int> left(bar.begin(), bar.begin() + mid);
std::vector<int> right(bar.begin() + mid, bar.end());
mergeSort(left);
mergeSort(right);
merge(left, right, bar);
}
int main() {
std::vector<int> v = {38, 27, 43, 3, 9, 82, 10};
mergeSort(v);
for (int i = 0; i < v.size(); i++) {
std::cout << v[i] << " ";
}
return 0;
}
Output:
8 9 10 27 38 43 82
This program illustrates how I can use merge sort to sort a vector.
From the experiences I've had with sorting in C++, these are some important points I picked up:
If you want to improve your skills in software engineering, especially in algorithms and data structures, think about checking courses at upGrad. They have detailed programs that aim to transform new software engineers such as myself into professionals ready for the industry.
Sorting is a strong skill for someone who programs in C++. When I know and use the correct sorting methods, my software works faster and with more dependability. Using built-in functions or creating your own sorting methods, the advantages in flexibility and performance improvement justify the work put into it.
To continue learning and grow professionally in the field of software engineering, especially to understand algorithms and data structures better, look at the classes offered by upGrad. The courses taught by specialists are a great method for improving your abilities and moving forward in your job.
1. What is sorting in C++?
In C++ language, we make an order for the items inside a place like array or list. Most times, we arrange from small to big or other way around. We do this by choosing different ways of sorting that work fast or slow depending on method.
2. What are the common sorting algorithms in C++?
In C++ we often use sorting methods like Bubble Sort, Selection Sort, Insertion Sort, together with Merge Sort, Quick Sort and also Heap Sort.
3. How do I perform sorting in C++?
To sort in C++, the std::sort function from <algorithm> header is useful for many situations. If you need a special kind of sorting, you could create your own method such as Quick Sort or Merge Sort.
4. What is the time complexity of sorting algorithms in C++?
The time complexity varies:
O(n^2): Bubble Sort, Selection Sort, Insertion Sort
O(n log n): Merge Sort, Quick Sort, Heap Sort
5. When should I use which sorting algorithm in C++?
Use Quick Sort for general purposes due to its average-case efficiency.
Use Merge Sort for guaranteed O(n log n) performance.
Use Insertion Sort for small or nearly sorted data sets.
6. Can I sort custom data types in C++?
You can arrange custom data types in order by either adding new definitions for the comparison operators or giving a unique comparison function to the algorithm that does sorting.
7. What is stable sorting in C++?
A consistent sorting keeps the original sequence of items that have matching values. In C++, you use std::stable_sort to make sure this happens.
8. Is sorting in C++ affected by the data type of elements?
Certainly, how sorting acts and performs might change because of the kind of data in elements since comparing them can be different and sometimes you need to switch one type to another.
Author
Start Learning For Free
Explore Our Free Software Tutorials and Elevate your Career.
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.