Array Sorting Functions in C++
C++ provides several built-in functions for sorting arrays, making it easy to organize data in ascending or descending order. Here are some of the most commonly used sorting functions:
1. std::sort()
This function is part of the <algorithm>
header file and offers a highly efficient sorting algorithm.
Syntax:
#include
#include
int main() {
int arr[] = {5, 2, 9, 1, 5};
int n = sizeof(arr) / sizeof(arr[0]);
std::sort(arr, arr + n); // sorts in ascending order
for (int i = 0; i < n; i++) {
std::cout << arr[i] << " ";
}
std::cout << std::endl;
return 0;
}
Explanation:
std::sort(arr, arr + n)
: This line sorts the arrayarr
from the beginning (arr
) to the end (arr + n
).- The function sorts the array in ascending order by default.
- To sort in descending order, use
std::sort(arr, arr + n, std::greater<int>());
.
2. std::stable_sort()
This function is similar to std::sort()
but guarantees that elements with the same value maintain their relative order.
Syntax:
#include
#include
int main() {
int arr[] = {5, 2, 9, 1, 5};
int n = sizeof(arr) / sizeof(arr[0]);
std::stable_sort(arr, arr + n);
for (int i = 0; i < n; i++) {
std::cout << arr[i] << " ";
}
std::cout << std::endl;
return 0;
}
Explanation:
std::stable_sort(arr, arr + n)
: This line sorts the arrayarr
while preserving the relative order of elements with the same value.
3. std::qsort()
This function is from the <cstdlib>
header file and uses the quicksort algorithm for sorting.
Syntax:
#include
#include
int compare(const void* a, const void* b) {
return (*(int*)a - *(int*)b);
}
int main() {
int arr[] = {5, 2, 9, 1, 5};
int n = sizeof(arr) / sizeof(arr[0]);
qsort(arr, n, sizeof(arr[0]), compare);
for (int i = 0; i < n; i++) {
std::cout << arr[i] << " ";
}
std::cout << std::endl;
return 0;
}
Explanation:
qsort(arr, n, sizeof(arr[0]), compare)
: This line sorts the arrayarr
using quicksort algorithm.compare
is a custom function to define the sorting criteria (ascending order in this case).
Remember:
std::sort()
andstd::stable_sort()
are typically preferred due to their efficiency and ease of use.std::qsort()
is generally less efficient than the algorithms used bystd::sort()
andstd::stable_sort()
.
These sorting functions provide powerful tools for organizing data in C++. Choosing the appropriate function depends on your specific needs and the characteristics of your data.