C++中sort与qsort函数简介

来源:互联网 发布:淘宝流量包怎么购买 编辑:程序博客网 时间:2024/05/15 10:59

C++中自带了一些排序函数,其中STL的sort();qsort()用的较多

sort:复杂度为n*log2(n)

头文件

#include <algorithm> 

原型:

template <class RandomAccessIterator>
 void sort ( RandomAccessIterator first, RandomAccessIterator last );
 
template <class RandomAccessIterator,class Compare>
 void sort ( RandomAccessIterator first, RandomAccessIterator last, Compare comp );

bool compare(int a,int b)
{
      return a<b;   //升序排列,如果改为return a>b,则为降序

}


qsort:
原型:
void qsort(void *base, int nelem, unsigned int width, int ( * pfCompare)( const void *, const void *));

参数分别是数组指针,元素个数,每个元素大小(sizeof),比较函数

比较函数自己定义,如 int compare(const void *a,const void *b) 。

若*a排在*b前,返回负值

*a排在*b前后都行,返回0

*a排在*b后面,返回正值

显然,返回值并不依赖大小,还依赖排序的要求;

示例:

#include #include #include using namespace std;int compare(const void *a, const void *b){    int pca = *(int *)a;    int pcb = *(int *)b;    return (pca-pcb) ;  //从小到大排序    //return (pcb-pca) ;//从大到小排序}int 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] << " " ;    return 0;}