我们讨论过 C中的qsort()。 C++ STL提供了类似的函数排序,它对向量或数组进行排序(具有随机访问的项)。
它通常需要两个参数,第一个是数组/向量的点,排序需要从这里开始,第二个参数是我们希望数组/向量排序的长度。第三个参数是可选的,可以在需要按字典顺序对元素进行排序的情况下使用。
默认情况下,sort()函数按升序对元素进行排序。
下面是一个简单的程序来显示sort()的工作情况。
CPP
// C++ program to demonstrate default behaviour of // sort() in STL. #include <bits/stdc++.h> using namespace std; int main() { int arr[] = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 }; int n = sizeof (arr) / sizeof (arr[0]); /*Here we take two parameters, the beginning of the array and the length n upto which we want the array to be sorted*/ sort(arr, arr + n); cout << "Array after sorting using " "default sort is : " ; for ( int i = 0; i < n; ++i) cout << arr[i] << " " ; return 0; } |
输出:
Array after sorting using default sort is : 0 1 2 3 4 5 6 7 8 9
如何按降序排序? sort()接受第三个参数,用于指定元素的排序顺序。我们可以通过“greater()”函数按降序排序。该函数以一种将更大的元素放在前面的方式进行比较。
CPP
// C++ program to demonstrate descending order sort using // greater<>(). #include <bits/stdc++.h> using namespace std; int main() { int arr[] = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 }; int n = sizeof (arr) / sizeof (arr[0]); sort(arr, arr + n, greater< int >()); cout << "Array after sorting : " ; for ( int i = 0; i < n; ++i) cout << arr[i] << " " ; return 0; } |
输出:
Array after sorting : 9 8 7 6 5 4 3 2 1 0
如何在邮件中排序 特殊订单? 我们还可以编写自己的比较器函数,并将其作为第三个参数传递。这个“比较器”函数返回一个值;可转换为bool,它基本上告诉我们,通过的“first”参数是否应该放在通过的“second”参数之前。 例如:在下面的代码中,假设区间{6,8}和{1,9}作为参数在“compareInterval”函数(comparator函数)中传递。现在是i1。首先(=6)
CPP
// A C++ program to demonstrate // STL sort() using // our own comparator #include <bits/stdc++.h> using namespace std; // An interval has a start // time and end time struct Interval { int start, end; }; // Compares two intervals // according to starting times. bool compareInterval(Interval i1, Interval i2) { return (i1.start < i2.start); } int main() { Interval arr[] = { { 6, 8 }, { 1, 9 }, { 2, 4 }, { 4, 7 } }; int n = sizeof (arr) / sizeof (arr[0]); // sort the intervals in increasing order of // start time sort(arr, arr + n, compareInterval); cout << "Intervals sorted by start time : " ; for ( int i = 0; i < n; i++) cout << "[" << arr[i].start << "," << arr[i].end << "] " ; return 0; } |
输出:
Intervals sorted by start time : [1,9] [2,4] [4,7] [6,8]
std::sort()的时间复杂度为: 1.最佳情况–O(N日志N) 2.平均情况–O(N对数N) 3.最坏情况–O(N日志N)
空间复杂度——它可能会使用O(logn)辅助空间。
?列表=PLQM7ALHXFYSGG6GSRME2IN4K8FPH5QVB
本文由 Shubham Agrawal 。如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请发表评论