编程时排序经常会用到,幸运的是C语言已经为我们准备了一个非常好的函数qsort,它可以给任意数组进行排序。在C语言的<stdlib.h>中,qsort原型是 这样的
void qsort(void *base, size_t nmemb, size_t size, int (*compar) (const * void *, const void * ));
其中,base指向数组的第一个元素,nmumb为排序元素的数量,size是数组中元素的大小,compar为指向比较函数的指针,用户根据需要自定义比较函数。
下面的程序自定义了一个比较函数,调用qsort,简单实现对字符串的排序功能:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define MAX_LEN 20
#define STR_NUM 50
#define MOL_ERR 1
char * myMollac();
int compare_str(const void *p, const void *q);
void print_list(char *p[],int num);
int main(){
char * p[STR_NUM]; //存放字符串指针
for(int i=0;i<STR_NUM;i++)
p[i]=NULL;
int i=0;
char *s=myMollac();
printf("input words(-1 to quit):");
scanf("%s",s);
getchar();
while (i<STR_NUM && strcmp(s,"-1")!=0){
p[i]=s;
//printf("%s\n",p[i]);
i++;
s=myMollac();
printf("input words(-1 to quit):");
scanf("%s",s);
getchar();
}
qsort(p,i,sizeof(s),compare_str);
print_list(p,i);
system("pause");
return 0;
}
char * myMollac(){
char *s=(char *)malloc(MAX_LEN+1);
if(!s){
printf("memory allocate failed!\n");
exit (MOL_ERR);
}
return s;
}
int compare_str(const void *p, const void *q){
return strcmp(*(char **)p, *(char **)q);
}
void print_list(char * p[],int num){
if (num==0)
return ;
int i=0;
while((p[i])!=NULL&& (p[i+1])!=NULL && i<num){
printf("%s -> ",p[i]);
i++;
}
printf("%s\n\n",p[i]);
}
结果如图:


微信扫一扫,订阅我的博客动态^_^