排序算法属于C++泛型算法中的一种,以不同的方式为容器的元素排序。这些算法包括sort, stable_sort, partial_sort, partial_sort_copy以及一些相关的功能,包括nth_element, binary_search, lower_bound, upper_bound, equal_range, merge, includes, push_heap, pop_heap, make_heap, sort_heap, set_union, set_intersection, set_difference, set_symmetric_difference, min, min_element, max, max_element, lexicographical_compare, next_permutation, prev_permutation。由于相关功能不常用,这里就不具体介绍了,下面用程序实例演示每一个算法。
1、sort——根据容器内的元素类型给元素重新排序,例如string类型按字母表先后排序;
#include <algorithm>
#include <iostream>
#include <string>
int main ()
{
vector<string> s;
s.push_back("Deny");
s.push_back("Zifrid");
s.push_back("Andry");
s.push_back("Arnold");
sort(s.begin(), s.end());
ostream_iterator<string> it (cout, "\n");
copy(s.begin(), s.end(), it);
return 0;
}
运行结果:
// Andry
// Arnold
// Deny
// Zifrid
2、stable_sort——传参给指定函数,并根据指定函数返回值的真假给元素排序,条件处理后处于同一级别的保持原有先后顺序;
#include <iostream>
#include <algorithm>
#include <cctype>
#include <cstdio>
using namespace std;
inline bool lt_nocase(char c1, char c2)
{
return tolower(c1) < tolower(c2);
}
//-------------------------------------
int main()
{
char A[] = "fdBeACFDbEac";
const int N = sizeof(A) - 1;
stable_sort(A, A+N, lt_nocase);
printf("%s\n", A);
return 0;
}
运行结果:
// AaBbCcdDeEfF
3、partial_sort——对给定区间所有元素部分排序,下面实例是取最小的5个元素升序排列,剩下的元素不关心;
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int A[] = {7, 2, 6, 11, 9, 3, 12, 10, 8, 4, 1, 5};
const int N = sizeof(A) / sizeof(int);
partial_sort(A, A + 5, A + N);
copy(A, A + N, ostream_iterator<int>(cout, " "));
return 0;
}
运行结果:
// 1 2 3 4 5 11 12 10 9 8 7 6
4、partial_sort_copy——将排序结果拷贝到指定区间,拷满为止。
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
int A[] = {7, 2, 6, 11, 9, 3, 12, 10, 8, 4, 1, 5};
const int N = sizeof(A) / sizeof(int);
vector V(4);
partial_sort_copy(A, A + N, V.begin(), V.end());
copy(V.begin(), V.end(),
ostream_iterator<int>(cout, " "));
return 0;
}
运行结果:
// 1 2 3 4
除非注明,文章均为CppLive 编程在线原创,转载请注明出处,谢谢。



