# sort和qsort排序

qsort(数组名,数组长度,数组中每个元素大小,compare); compare函数的写法决定了排序是升序还是降序。需要#include<stdlib.h>

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

sort(数组名,数组末地址,compare) //若不写compare则默认升序排列，需要#include<algorithm>

sort(a,a+10); //将数组a以升序排序，假设先前定义了a[10]并输入了数据

int num[100];

int cmp ( const void *a , const void *b )
{
return *(int *)a – *(int *)b;
}

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

char word[100];

int cmp( const void *a , const void *b )
{
return *(char *)a – *(int *)b;
}

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

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

Problem Description

Input

Output

Sample Input

Sample Output