C++ STL 排序函数


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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值