您的位置:首页 > 编程语言 > C语言/C++

C++ STL 排序函数

2016-03-31 16:19 375 查看
C++的写法:

sort和stable_sort可对原生数组、STL容器排序,sort采用快排实现,不稳定,stable_sort采用归并排序实现,稳定,时间复杂度均为N*log(N)

//一般排序
//sort stable_sort在<algorithm>中
//函数原型 void sort(_RanIt _First, _RanIt _Last, _Pr _Pred)
//参考 http://www.cplusplus.com/reference/algorithm/sort/ #include <string>
#include <vector>
#include <algorithm>
#include <iostream>

using namespace std;

template <typename t>
void Print (vector<t> array)
{
int size = array.size();
cout << "size: " << size << endl;
for (int i = 0; i < size; ++i)
{
cout << array[i] << endl;
}
}

bool CompIntLess(int first,int second)
{
return (first) < (second);
}

bool CompIntGreater(int first,int second)
{
return (first) > (second);
}

void SortInt()
{
vector<int> array;
array.push_back(4);
array.push_back(5);
array.push_back(1);
array.push_back(2);

//排序
cout << "sort with from small to big" << endl;
sort(array.begin(),array.end(),less<int>());
Print(array);
cout << "sort with from big to small" << endl;
sort(array.begin(),array.end(),greater<int>());
Print(array);

//稳定排序
cout << "sort with from small to big" << endl;
stable_sort(array.begin(),array.end(),less<int>());
Print(array);
cout << "sort with from big to small" << endl;
stable_sort(array.begin(),array.end(),greater<int>());
Print(array);

//自写compare函数排序
cout << "sort with from small to big" << endl;
sort(array.begin(),array.end(),CompIntLess);
Print(array);
cout << "sort with from big to small" << endl;
sort(array.begin(),array.end(),CompIntGreater);
Print(array);
}

void SortIntArray()
{
int a[10] = {5, 6, 4, 3, 7, 0 ,8, 9, 2, 1};

cout << "sort with from small to big" << endl;
sort(a, a + 10, less<int>());
for (int i = 0; i < 10; i++)
cout << a[i] << " " << endl;
cout << "sort with from big to small" << endl;
sort(a, a + 10, greater<int>());
for (int i = 0; i < 10; i++)
cout << a[i] << " " << endl;
}

int main(){
SortInt();
SortIntArray();

int ttt = 0;

return 0;
}


C的写法:

qsort只能对原生数组排序,不能对STL容器排序

//快速排序
//qsort在<stdlib.h>中
//函数原型 void qsort(void * _Base, int _NumOfElements, int _SizeOfElements, int (* _PtFuncCompare)(const void *, const void *));
//参考 http://www.cplusplus.com/reference/cstdlib/qsort/ #include <iostream>
#include <stdlib.h>

using namespace std;

int compare(const void *a, const void *b)
{
int *pa = (int*)a;
int *pb = (int*)b;
return (*pa) - (*pb);  //从小到大排序
}

void main()
{
int a[10] = {5, 6, 4, 3, 7, 0 ,8, 9, 2, 1};
qsort(a, 10, sizeof(int), compare);
for (int i = 0; i < 10; i++)
cout << a[i] << " " << endl;

int ttt = 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: