C語言qsort函數使用

編程時排序經常會用到,幸運的是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]);
}

結果如圖:


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章