在这里,我们将看到如何使用sort()
C ++ STL函数对数组进行排序,因此,如果数组类似于A = [52,14,85,63,99,54,21],则输出将为[14 21 52 54 63 85 99]。排序时,我们将使用sort()
头文件<algorithm>中提供的函数。代码如下-
#include <iostream> #include <algorithm> using namespace std; int main() { int arr[] = {52, 14, 85, 63, 99, 54, 21}; int n = sizeof(arr) / sizeof(arr[0]); cout << "Array before sorting: "; for (int i = 0; i < n; i++) cout << arr[i] << " "; sort(arr, arr + n); cout << "\nArray after sorting: "; for (int i = 0; i < n; i++) cout << arr[i] << " "; }
输出结果
Array before sorting: 52 14 85 63 99 54 21 Array after sorting: 14 21 52 54 63 85 99