天之道

享受编程的乐趣。
posts - 118, comments - 7, trackbacks - 0, articles - 0
  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

字符串排序

Posted on 2012-08-19 10:49 hoshelly 阅读(394) 评论(0)  编辑 收藏 引用 所属分类: CProgramming
//字符串排序,利用qsort函数
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define Nmax 1000
#define Mmax 10000
char buf[Mmax]; int M=0;
int compare(const void *i, const void *j)
{
    return strcmp(*(char **)i, *(char **)j);
}

int main()
{
    int i, N;
    char *a[Nmax];
    for(N=0; N<Nmax; N++)
    {
        a[N]= &buf[M];
        if(scanf("%s", a[N]) == EOF) break;
        M+=strlen(a[N])+1;
    }

    qsort(a,N,sizeof(char*),compare); //四个参数分别代表:待排序的数组首地址,数组中待排序的元素数量,各元素占用的空间,排序函数(确定排序顺序)
    for(i=0;i<N;i++)
        printf("%s\n",a[i]);

    return 0;
}

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理