C語言qsort函式的使用

再來一隻皮皮發表於2020-10-02

函式原型:void qsort(void *base, int nelem, int width, int(*fcmp)(const void *, const *))

標頭檔案:#include<stdlib.h>

base:要排序的陣列
nelem:需要排序的長度
width:每個陣列元素的大小
cmp:比較函式

int型別的排序

int cmp1(const void *a,const void *b){ //int型別排序 ,從小到大排序 
	int s1 = *(int *)a; 
	int s2 = *(int *)b; 
	if(s1>s2)
		return 1;
	else if(s1==s2)
		return 0;
	else
		return -1;
}
int main{
	int p[10] = {4,8,9,43,56,83,6,233,4,5};
	qsort(p,10,sizeof(int),cmp1); //呼叫qsort 
	return 0;
}

double型別排序

int cmp2(const void *a,const void *b){//double型別排序 ,從小到大排序 
	double s1 = *(double *)a; 
	double s2 = *(double *)b; 
	if(s1>s2)
		return 1;
	else if(s1==s2)
		return 0;
	else
		return -1;
}
int main{
	double d[6] = {12.1,3.4,33.2,76.5,5.5,7.6};
	qsort(d,6,sizeof(double),cmp2); //呼叫qsort 
	return 0;
}

char型別排序

int cmp3(const void *a,const void *b){//char型別排序 ,從小到大排序 
	char s1 = *(char *)a; 
	char s2 = *(char *)b; 
	if(s1>s2)
		return 1;
	else if(s1==s2)
		return 0;
	else
		return -1;
}
int main{
	char c[10] = {'d','a','r','q','p','b','c','x','j','f'}; 
	qsort(c,10,sizeof(c[0]),cmp3); //呼叫qsort 
	return 0;
}

字串型別排序

int cmp4(const void *a,const void *b){//字串型別排序 ,從小到大排序 按字典序 
	char *s1 = (char *)a;   //s1,s2用指標 
	char *s2 = (char *)b; 
	if(strcmp(s1,s2)>0)
		return 1;
	else if(strcmp(s1,s2)==0)
		return 0;
	else
		return -1;
}
int main{
	char s[6][5] = {"faf","fdas","ewew","dss","qwer","ffcs"};
	qsort(s,6,sizeof(s[0]),cmp4); //呼叫qsort 
	return 0;
}

結構體型別排序

struct stu{
	char s[10];
	int num; 
};
int cmp5(const void *a,const void *b){//對結構體的 s 進行排序 ,從小到大排序
	struct stu s1 = *(struct stu *)a;
	struct stu s2 = *(struct stu *)b;
	if(strcmp(s1.s,s2.s)>0)
		return 1;
	else if(strcmp(s1.s,s2.s)==0)
		return 0;
	else
		return -1;
}
int main{
	struct stu st[4];
	strcpy(st[0].s,"張三");
	strcpy(st[1].s,"李四");
	strcpy(st[2].s,"王五");
	strcpy(st[3].s,"大錘");
	st[0].num = 43; 
	st[1].num = 5; 
	st[2].num = 36;
	st[3].num = 3; 
	qsort(st,4,sizeof(st[0]),cmp5); //呼叫qsort 
	return 0;
}

相關文章