sort和qsort一些用法的总结

来自一位学长

qsort排序(从大到小)

#include <stdlib.h>
#include <stdio.h>
int a[105];
int cmp(const void *x,const void *y)
{
    return (*(int*)x)>(*(int*)y);
}
int main()
{
    int i, j;
    a[0]=8,a[1]=1, a[2]=3, a[3]=-3;
    qsort(a,4,sizeof(a[0]),cmp);
    for(i=0;i<=3;i++) printf("%d\n",a[i]);
    return 0;
}

qsort对结构体排序

#include<algorithm>
#include<cstring>
#include<string>
#include<cstdio>
#include<stdlib.h>
using namespace std;
struct DATA
{
    int a, b;
} dt[1005];
int cmp(const void *x,const void *y)
{
    return ((DATA*)x)->a-((DATA*)y)->a;
}
int main()
{
    int i;
    dt[0].a=1, dt[0].b=-1;
    dt[1].a=3, dt[1].b=-2;
    dt[2].a=-1, dt[2].b=3;
    qsort(dt,3,sizeof(dt[0]),cmp);
	for(i=0;i<3;i++)
		printf("%d %d\n",dt[i].a,dt[i].b);
    return 0;
}


qsort对字符排序

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int cmp(const void *a,const void *b)
{
	return strcmp((char *)a,(char *)b);
}
char s[1000005][205];
int main(void)
{
	int i,j,n;
	char ch,temp[205];
	i=j=0;
	memset(s,0,sizeof(s));
	memset(temp,0,sizeof(temp));
	while(scanf("%c",&ch)!=EOF)
	{
		if(ch>='a'&&ch<='z') {s[i][j]=ch;j++;}
		else if(ch>='A'&&ch<='Z') {s[i][j]=ch+32;j++;}
		else if(j!=0) {s[i][j]='\0';j=0;i++;}
	}
	n=i+1;
	qsort(s,i,sizeof(s[0]),cmp);
	for(i=0;i<n;i++)
		if(strcmp(s[i],s[i+1])!=0) printf("%s\n",s[i]);
	return 0;
}


sort对结构体排序

#include<algorithm>
#include<cstring>
#include<string>
#include<cstdio>
#include<stdlib.h>
using namespace std;
struct DATA
{
    int a, b;
} dt[1005];
bool cmp(DATA x,DATA y)
{
    return x.a<y.a;
}
int main()
{
    int i, j;
    dt[0].a=1, dt[0].b=-1;
    dt[1].a=3, dt[1].b=-2;
    dt[2].a=-1, dt[2].b=3;
    sort(dt,dt+3,cmp);
    return 0;
}


重载sort

#include<algorithm>
#include<cstring>
#include<string>
#include<cstdio>
#include<stdlib.h>
using namespace std;
struct DATA
{
    int a, b;
    bool operator<(const DATA &y)const
    {
        return a<y.a;
    }
} dt[1005];
int main()
{
    int i, j;
    dt[0].a=1, dt[0].b=-1;
    dt[1].a=3, dt[1].b=-2;
    dt[2].a=-1, dt[2].b=3;
    sort(dt,dt+3);
    return 0;
}



版权声明:本文为博主原创文章,未经博主允许不得转载。http://xiang578.top/

posted @ 2015-02-12 09:39  xryz  阅读(210)  评论(0编辑  收藏  举报