sort

sort  头文件  #include<algorithm>
      +   using namespace std;


1.一维数组排序
#include<stdio.h>
#include<stdlib.h>
#include<algorithm>
using namespace std;
bool cmp(int a,int b)//如果是double型的,参数改为double a,double b
{
    return a<b;//升序
}
int main()
{
    int a[100];
    int i;
    int n;
    scanf("%d",&n);
    for(i=0;i<=n-1;i++)
        scanf("%d",a+i);
    sort(a,a+n,cmp);
    for(i=0;i<=n-1;i++)
        printf("%d ",a[i]);
}


2.多个字符串排序


#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<algorithm>
using namespace std;
bool cmp(char *a,char *b)
{
    return strcmp(a,b)<0;
}
int main()
{
    char s[100][100];
    char *p[100];
    int i;
    int n;
    scanf("%d",&n);
    getchar();
    for(i=0; i<=n-1; i++)
    {
        gets(s[i]);
        p[i]=s[i];
    }
    sort(p,p+n,cmp);
    for(i=0; i<=n-1; i++)
        printf("%s ",p[i]);
}






3.对结构体进行排序




#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<algorithm>
using namespace std;
struct node
{
    int x;
    int y;
}s[100];
bool cmp(struct node p,struct node q)//如果x相等按照y从小到大排序,否则按照x从小到大排序。
{
    if(p.x==q.x)
        return p.y<q.y;
    return p.x<q.x;
}
int main()
{
    int i;
    int n;
    scanf("%d",&n);
    for(i=0; i<=n-1; i++)
        scanf("%d %d",&s[i].x,&s[i].y);
    sort(s,s+n,cmp);
    for(i=0; i<=n-1; i++)
        printf("%d %d ",s[i].x,s[i].y);
}

原文地址:https://www.cnblogs.com/jk17211764/p/9677428.html