您的位置:首页 > 其它

qsort函数用法

2013-06-12 02:20 239 查看
qsort
void qsort (void* base, size_t num, size_t size,
            int (*compar)(const void*,const void*));
Sort elements of array
Sorts the num elements of the array pointed by base, each element size bytes long, using the compar function to determine the order.

The sorting algorithm used by this function compares pairs of elements by calling the specified compar function with pointers to them as argument.

The function does not return any value, but modifies the content of the array pointed by base reordering its elements as defined by compar.

The order of equivalent elements is undefined.

Parameters
base
Pointer to the first object of the array to be sorted, type-casted to a void*.
num
Number of elements in the array pointed by base.
size_t is an unsigned integral type.
size
Size in bytes of each element in the array.
size_t is an unsigned integral type.
compar
Pointer to a function that compares two elements.
This function is called repeatedly by qsort to compare two elements. It shall follow the following prototype:
 
int compar (const void* p1, const void* p2);

Taking two pointers as arguments (both type-casted to const void*). The function defines the order of the elements by returning (in a stable and transitive manner):
return value	meaning
<0	The element pointed by p1 goes before the element pointed by p2
0	The element pointed by p1 is equivalent to the element pointed by p2
>0	The element pointed by p1 goes after the element pointed by p2

For types that can be compared using regular relational operators, a general compar function may look like:

1
2
3
4
5
6
int compareMyType (const void * a, const void * b)
{
  if ( *(MyType*)a <  *(MyType*)b ) return -1;
  if ( *(MyType*)a == *(MyType*)b ) return 0;
  if ( *(MyType*)a >  *(MyType*)b ) return 1;
}

Return Value
none

Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/* qsort example */
#include <stdio.h>      /* printf */
#include <stdlib.h>     /* qsort */

int values[] = { 40, 10, 100, 90, 20, 25 };

int compare (const void * a, const void * b)
{
  return ( *(int*)a - *(int*)b );
}

int main ()
{
  int n;
  qsort (values, 6, sizeof(int), compare);
  for (n=0; n<6; n++)
     printf ("%d ",values
);
  return 0;
}

Output:

10 20 25 40 90 100


qsort   功 能: 使用快速排序例程进行排序   

用 法: void qsort(void *base, int nelem, int width, int (*fcmp)(const void *,const void *));   

各参数:1 待排序数组首地址 2 数组中待排序元素数量 3 各元素的占用空间大小 4 指向函数的指针

用于确定排序的顺序 排序方法有很多种, 选择排序,冒泡排序,归并排序,快速排序等。 看名字都知道快速排序 是目前公认的一种比较好的排序算法(我没听书速度比这快的了,特殊场合例外),比选择排序,冒泡排序都要快。这是因为他速度很快,所以系统也在库里实现这个算法,便于我们的使用。 这就是qsort。

qsort 要求提供一个 比较函数,是为了做到通用性更好一点。比如你不仅仅的是要排序一个数字而已,可能你要用来排序几个数字 ,比如有一个结构 struct num { int a; int b; }; 然后我有一个num 类型的数组, num dddd[100]; 我想给 dddd这个数组排序,那怎么办? 我想让 a +b 最大的num元素排在数组的最前面,那又怎么办? 这都可以通过定义比较函数来做到的。 比较函数的作用就是给qsort指明
元素的大小是怎么比较的。 像这样的比较函数 inline int MyCmp(const void* a, const void* b) 都是有两个元素 作为参数,返回一个int 值, 如果 比较函数返回大于0,qsort就认为 a>b , 如果比较函数返回等于0 qsort就认为a 和b 这两个元素相等,返回小于零 qsort就认为 ab),你比较函数却返回一个 -1 (小于零的)那么qsort认为a<本文中排序都是采用的从小到大排序>

一、对int类型数组排序

int num[100];

Sample: int cmp ( const void *a , const void *b )

{ return *(int *)a - *(int *)b; }

qsort(num,100,sizeof(num[0]),cmp);

二、对char类型数组排序(同int类型)

char word[100];

Sample: int cmp( const void *a , const void *b )

{ return *(char *)a - *(int *)b; }

qsort(word,100,sizeof(word[0]),cmp);

三、对double类型数组排序(特别要注意)

double in[100];

int cmp( const void *a , const void *b )

{ return *(double *)a > *(double *)b ? 1 : -1; }

qsort(in,100,sizeof(in[0]),cmp);

四、对结构体一级排序

struct In { double data; int other; }s[100]

//按照data的值从小到大将结构体排序,关于结构体内的排序关键数据data的类型可以很多种,

//参考上面的例子写

int cmp( const void *a ,const void *b)

{ return (*(In *)a).data > (*(In *)b).data ? 1 : -1; }

qsort(s,100,sizeof(s[0]),cmp);

五、对结构体二级排序

struct In { int x; int y; }s[100];

//按照x从小到大排序,当x相等时按照y从大到小排序

int cmp( const void *a , const void *b )

{

struct In *c = (In *)a; struct In *d = (In *)b;

if(c->x != d->x)

return c->x - d->x;

else

return d->y - c->y;

}

qsort(s,100,sizeof(s[0]),cmp);

六、对字符串进行排序

struct In { int data; char str[100]; }s[100];

//按照结构体中字符串str的字典顺序排序

int cmp ( const void *a , const void *b )

{

return strcmp( (*(In *)a)->str , (*(In *)b)->str );

}

qsort(s,100,sizeof(s[0]),cmp);

七、计算几何中求凸包的cmp

int cmp(const void *a,const void *b)

//重点cmp函数,把除了1点外的所有点,旋转角度排序

{

struct point *c=(point *)a;

struct point *d=(point *)b;

if( calc(*c,*d,p[1]) < 0)

return 1;

else if( !calc(*c,*d,p[1]) && dis(c->x,c->y,p[1].x,p[1].y) < dis(d->x,d->y,p[1].x,p[1].y))

//如果在一条直线上,则把远的放在前面

return 1;

else return -1;

}

    快速排序qsort真的很强大

一、对int类型数组排序

int num[100];

int cmp ( const void *a , const void *b )

{

return *(int *)a - *(int *)b;

}

qsort(num,100,sizeof(num[0]),cmp);

二、对char类型数组排序(同int类型)

char word[100];

int cmp( const void *a , const void *b )

{

return *(char *)a - *(int *)b;

}

qsort(word,100,sizeof(word[0]),cmp);

三、对double类型数组排序

double in[100];

int cmp( const void *a , const void *b )

{

return *(double *)a > *(double *)b ? 1 : -1;

}

qsort(in,100,sizeof(in[0]),cmp);

四、对结构体一级排序

struct Sample

{

double data;

int other;

}s[100]

//按照data的值从小到大将结构体排序

int cmp( const void *a ,const void *b)

{

return (*(Sample *)a).data > (*(Sample *)b).data ? 1 : -1;

}

qsort(s,100,sizeof(s[0]),cmp);

五、对结构体二级排序

struct Sample

{

int x;

int y;

}s[100];

//按照x从小到大排序,当x相等时按照y从大到小排序

int cmp( const void *a , const void *b )

{

struct Sample *c = (Sample *)a;

struct Sample *d = (Sample *)b;

if(c->x != d->x) return c->x - d->x;

else return d->y - c->y;

}

qsort(s,100,sizeof(s[0]),cmp);

六、对字符串进行排序

struct Sample

{

int data;

char str[100];

}s[100];

//按照结构体中字符串str的字典顺序排序

int cmp ( const void *a , const void *b )

{

return strcmp( (*(Sample *)a)->str , (*(Sample *)b)->str );

}

qsort(s,100,sizeof(s[0]),cmp);

附加一个完整点的代码,对字符串二维数组排序:

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

char s[2001][1001];

int cmp(const void *a, const void *b){

return strcmp((char *)a,(char *)b);

}

int main(){

int i,n;

scanf("%d",&n);

getchar();

for(i=0;i<n;i++) gets(s[i]);

qsort(s,n,1001*sizeof(char),cmp);

for(i=0;i<n;i++) puts(s[i]);

return 0;

}

如果是一个结构体的话:

struct node{

int x,y;

}

按x排序的话,就这样用:

bool comp(const &a,const &b){return a.x

这里关键要理解 & 这个符号

举个简单点的例子来说:

int a=10;

int &b=a;

这样b就和a完全一样啦

这个东东是相当好用的,比如我们想调用f(a,b,c)函数,并且希望对abc的值进行改变的话

。在c里面ms只可以用指针来实现。

但是用指针比较麻烦

有 & 这个符号就好用啦。


首先讲qsort,是快速排序,其包含在<stdlib.h>中

函数有四个参数,没有返回值:

qsort(s,n,sizeof(s[0]),cmp);其中cmp为比较函数;

s排序的首地址,n元素个数,sizeof(s[0])为单个元素大小;

由自己编写函数定义如下:

int cmp(const void *a,const void *b);返回值为int型值为1,0,-1;

注意:

(*(int *)a) < (*(int *)b); 返回只有0,1。

下面介绍几种结构体排序的比较函数:(无说明都为降序排列)

ElementType可以是数组中的存放的数据类型

(可以是char,int,double,etc);

1.对数组排序;

int cmp(const void *a,const void *b)

{

return *((ElementType *) a)>*((ElementType *)b)?1:-1;

}

2.对字符串排序

ine cmp(const void * a; const void *b)

{

return strcmp((char *)a,(char *)b);

}

3.按结构体中某个关键字排序(对结构体的一级排序)

struct Node

{

double data;

int other;

};

int cmp(const void *p1,const void *p2)

{

return (*(Node *)p2->data)>(*(Node *)p1->data)?1:-1;

}

4、计算几何中求凸包的Comp

//以下是俺从别人那儿抄来的,暂时还没用过

int Comp(const void *p1,const void *p2)

//重点Comp函数,把除了1点外的所有的点旋转角度排序

{

struct point *c=(point *)p1;

struct point *d=(point *)p2;

if( cacl(*c, *d,p[1]) < 0) return 1;

else if(!cacl(*c, *d, p[1]) && dis(c->x,c->y,p[1].x,p[1].y) < dis(d->x,d->y,p[1].x,p[1].y ) )

//如果在一条直线上,则把远的放在前面

return 1;

else return -1;

}

5.按结构体中多个关键字排序(对结构体多级排序)【以二级为例】:

struct Node

{

int x;

int y;

}

//按照x从小到大排序,当x相等时按y从大到小排序

int cmp(const void *p1,const void *p2)

{

struct Node *c = (Node *)p1;

struct Node *d = (Node *)p2;

if(c->x != d->x) return c->x-d->x;

else return d->y - c->y;

}

下面介绍sort函数:

sort()函数是c++中标准模板库的的函数,在qsort()上已经进行了优化,根据情况的不同可以采用不同的算法,所以较快。

在同样的元素较多和同样的比较条件下,sort()的执行速度都比qsort()要快。另外,sort()是类属函数,可以用于比较任何容器,任何元素,任何条件。

使用时需调用<algorithm>

sort(begin(),end(),cmp),

对于cmp函数bool cmp(node a,node b)对于a,b作为数组的单个的前后顺序,与qsort()的比较函数不同:

开始a在前,b在后,我们只需要写出使得a,b不用交换的条件返回true,其他的返回false。

今天在看程序时,遇见了sort()这个函数,我在网页上搜了一些资料,整合一下

sort()函数是C++中的排序函数其头文件为:#include<algorithm>头文件;qsort()是C中的排序函数,其头文件为:#include<stdlib.h>

先说一下qsort()吧,搜索到的资料容易懂一些。

六类qsort排序方法

qsort函数很好用,但有时不太会用比如按结构体一级排序、二级排序、字符串排序等。

函数原型:void qsort(void *base,size_t nelem,size_t width,int (*fcmp)(const void*,const void *))

输入参数:

base 待排序的数组,nelem 数组元数的个数(长度),width 每一个元素所占存储空间的大小,fcmp 用于对数组元素进行比较的函数的指针(该函数是要自己写的),返回值为1或-1(p1>p2则返回-1,p1<p2则返回1,p1==p2则返回0),size_t是int

输出参数:base 以升序排列

以下是其具体分类及用法(若无具体说明是以降序排列):

1、对一维数组排序:

(Element_type 是一位数组中存放的数据类型,可以是char,int,float,double,ect)

int comp(const void *p1,const void *p2)

{

return *((Element_type*)p2)>*((Element_type*)p1)?1:-1;

}

int main()

{

Element_type list[MAX];

initial(list);//这是对数组list[max]初始化

qsort(list, sizeof(list),sizeof(Element_type),Comp);//调用函数qsort

return 0;

}

2、对字符串排序:

int Comp(const void *p1,const void *p2)

{

return strcmp((char *)p2,(char *)p1);

}

int main()

{

char a[MAX1][MAX2];

initial(a);

qsort(a,lenth,sizeof(a[0]),Comp);

//lenth 为数组a的长度

3、按结构体中某个关键字排序(对结构体一级排序):

struct Node

{

double data;

int other;

}s[100];

int Comp(const void *p1,const void *p2)

{

return (*(Node *)p2)->data > (*(Node *)p1)->data ? 1 : -1;

}

qsort(s,100,sizeof(s[0]),Comp);

4、按结构体中多个关键字排序(对结构体多级排序)[以二级为例]:

struct Node

{

int x;

int y;

}s[100];

//按照x从小到大排序,当x相等时按y从大到小排序(这是3跟4的区别)

int Comp(const void *p1,const void *p2)

{

struct Node *c=(Node *)p1;

struct Node *d=(Node *)p2;

if(c->x!=d->x)

return c->x-d->x;

else

return d->y - c->y;

}

5、对结构体中字符串进行排序:

struct Node

{

int data;

char str[100];

}s[100];

//按照结构体中字符串 str 的字典序排序

int Comp(const void *p1,const void *p2)

{

return strcmp((*(Node *)p1).str,(*(Node *)p2).str);

}

qsort(s,100,sizeof(s[0],Comp);

6、计算几何中求凸包的Comp

int Comp(const void *p1,const void *p2)//重点Comp函数,把除了1点外的所有的点旋转角度排序

{

struct point *c=(point *)p1;

struct point *d=(point *)p2;

if( cacl(*c, *d,p[1])<0)

return 1;

else if(!cacl(*c, *d, p[1]) && dis(c->x,c->y,p[1].x,p[1].y)<dis(d->x,d->y,p[1].x,p[1].y ) )

//如果在一条直线上,则把远的放在前面

return 1;

else

return -1;

}

sort()函数说起来有一点模糊(没有比较系统的总结)

函数Sort()用于对参数整数数组array的元素进行由小到大的选择排序,其中参数n表示array数组中存储的数组元素数。例如,假设数组array中有10个元素,选择排序就是:先将10个数中的最小数与a[0]对换;再将a[1]到a[9]中的最小数与a[1]对换,….,直到排序完成。

这是我在百度上找到的1011题的答案,我觉得用它来说明sort()函数最具有代表性

#include <iostream>

#include <algorithm>

#include <cstdio>

#include <functional>

using namespace std;

int stick[100], n;

bool used[100];

//unused:没有使用的棍子的数目

//left:剩下的长度

//len:当前认为的计算的长度

bool dfs(int unused, int left, int len)

{

// 所有的棍子已经用了,且没有剩余的长度,符合搜索条件

if (unused == 0 && left == 0)

return true;

int i;

//没有剩下的.则新开一条棍子

if (left == 0)

left = len;

//寻找没有使用过的棍子

for (i=0; i<n; ++i)

{

//找到没有用过的,而且长度比left值要小(能够填进去)

if (!used && stick<=left)

{

//使用当前棍子

used = true;

//若在当前情况下能够扩展出正确答案,则返回

if (dfs(unused-1, left-stick, len))

//成功搜索,返回

return true;

//否则不使用当前的棍子

used = false;

//若使用stick不能扩展出正确结果,那么如果stick与left等长,则证明len不可能是正确答案

//若left与len等长,就是没有办法扩展

if (stick == left || left == len)

break;

}

}

//经过一轮搜索仍得不到正确答案,则返回false

return false;

}

int main()

{

int i, sum;

while (scanf("%d", &n) != EOF && n)

{

sum = 0;

for (i=0; i<n; ++i)

{

scanf("%d", &stick);

used = false;

sum += stick;

}

//先进行从大到小排序

sort(stick, stick+n, greater<int>());

//根据题目条件,从小向大寻找

for (i=stick[0]; i<=sum; ++i)

{

//棍子总长被i整除才进行搜索,否则没用

if (sum % i == 0)

{

if (dfs(n, 0, i))

{

printf("%d/n", i);

break;

}

}

}

}

return 0;

}

#include<algorithm>头文件
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: