algorithm库介绍之---- stable_sort()方法 与 sort()方法

文章转载自:http://www.cnblogs.com/ffhajbq/archive/2012/07/24/2607476.html

http://blog.csdn.net/godenlove007/article/details/7982450

关于stable_sort()和sort()的区别:

你发现有sort和stable_sort,还有 partition 和stable_partition, 感到奇怪吧。其中的区别是,带有stable的函数可保证相等元素的原本相对次序在排序后保持不变。或许你会问,既然相等,你还管他相对位置呢,也分不清 楚谁是谁了?这里需要弄清楚一个问题,这里的相等,是指你提供的函数表示两个元素相等,并不一定是一摸一样的元素。

例如,如果你写一个比较函数:

bool less_len(const string &str1, const string &str2)
{
        return str1.length() < str2.length();
}

此时,"apple" 和 "winter" 就是相等的,如果在"apple" 出现在"winter"前面,用带stable的函数排序后,他们的次序一定不变,如果你使用的是不带"stable"的函数排序,那么排序完 后,"Winter"有可能在"apple"的前面。

举例说明:

[cpp]  view plain  copy
 print ?
  1. #include <vector>  
  2.  #include <iostream>  
  3.  #include <algorithm>  
  4.    
  5.  using namespace std;  
  6.    
  7.  bool comp_as_int(double i, double j)  
  8.  {  
  9.      return (int(i)<int(j));  
  10.  }  
  11.    
  12.    
  13.  int main()  
  14.  {  
  15.      double mydoubles[] = {3.14, 1.41, 2.72, 4.67, 1.73, 1.32, 1.62, 2.58};  
  16.      vector<double> v;  
  17.      vector<double>::iterator it;  
  18.    
  19.      v.assign(mydoubles, mydoubles + 8);  
  20.        
  21.      cout<<"use default comparison:"<<endl;  
  22.      stable_sort(v.begin(), v.end());  
  23.    
  24.      for(it = v.begin(); it != v.end(); it++)  
  25.          cout<<*it<<" ";  
  26.      cout<<endl;  
  27.    
  28.      cout<<"use selfdefined comparison function comp_as_int():"<<endl;  
  29.      v.assign(mydoubles, mydoubles + 8);  
  30.      stable_sort(v.begin(), v.end(), comp_as_int);  
  31.        
  32.      for(it = v.begin(); it != v.end(); it++)  
  33.          cout<<*it<<" ";  
  34.      cout<<endl;  
  35.      cout<<"if it is not sorted with stable_sort(), the sequence of all elements between 1 and 2 will be set randomly..."<<endl;  
  36.    
  37.      return 0;  
  38.  }  

输出结果:

1 use default comparison:
2 1.32 1.41 1.62 1.73 2.58 2.72 3.14 4.67
3 use selfdefined comparison function comp_as_int():
4 1.41 1.73 1.32 1.62 2.72 2.58 3.14 4.67
5 if it is not sorted with stable_sort(), the sequence of all elements between 1 and 2 will be set randomly...



C ++ sort()与stable_sort() 

这两个函数的原理都是快速排序,时间复杂度在所有排序中最低,为O(nlog2n) ;   http://blog.sina.com.cn/s/blog_933dc4350100y9yk.html

sort的应用

1、可以传入两个参数;

     sort(a,a+N) ,其中a是数组,a+N表示对a[0]至a[N-1]的N个数进行排序(默认从小到大排序);

2、传入三个参数;

     sort(a,a+N,cmp),第三个参数是一个函数 ;

     如果让函数从大到小排序,可以用如下算法实现;

      bool cmp(int a,int b){return a>b};

      sort(A,A+N,cmp);

stable_sort的用法与sort一致,区别是stable_sort函数遇到两个数相等时,不对其交换顺序;这个应用在数组里面不受影响,当函数参数传入的是结构体时,会发现两者之间的明显区别;



  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值