C语言:qsort()的用法。


前言

使用qsort()函数,必须要引用#include<stdlib.h>
qsort(void* base, int sz, int width,int (* cmp)(void* e1,void* e2);
//base为要排列对象的起始地址;sz为要排列对象的总数;width为每个数据元素的宽度(字节数);
cmp为排列的函数指针,指向函数形参(const void* e1,const void* e2);若e1>e2,返回值为正数;若e1<e2,返回值为负数;若e1=e2,返回值为0。


一、排列整型数组

int cmp_int(const void* e1, const void* e2)
{
    
    
	//void* 可以接收任意类型的地址;
	//void* 不可以进行解引用操作;
	//void* p 不可以进行++--操作。
	return *(int*)e1 - *(int*)e2;
	//负值:e1<e2;
	//0:e1=e2;
	//正值:e1>e2。
}
void test1()//qsort()整型数组的用法。
{
    
    
	int arr[10] = {
    
     1,2,3,4,5,6,7,8,9,0 };
	int sz = sizeof(arr) / sizeof(arr[0]);
	qsort(arr, sz, sizeof(arr[0]), cmp_int);
	for (int i = 0; i < sz; i++)
	{
    
    
		printf("%d ", arr[i]);
	}
	printf("\n");
}

二、排列浮点型数组

int cmp_float(const void* e1, const void* e2)
{
    
    
	//void* 可以接收任意类型的地址;
	//void* 不可以进行解引用操作;
	//void* p 不可以进行++--操作。
	return (int)(*(float*)e1 - *(float*)e2);
	//负值:e1<e2;
	//0:e1=e2;
	//正值:e1>e2。
}
void test2()//qsort()整型数组的用法。
{
    
    
	float arr[10] = {
    
     1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,0.0 };
	int sz = sizeof(arr) / sizeof(arr[0]);
	qsort(arr, sz, sizeof(arr[0]), cmp_float);
	for (int i = 0; i < sz; i++)
	{
    
    
		printf("%.1f ", arr[i]);
	}
	printf("\n");
}

三、排列结构体

struct st
{
    
    
	char arr[20];
	int age;
};
int cmp_struct(const void* e1, const void* e2)
{
    
    
	//void* 可以接收任意类型的地址;
	//void* 不可以进行解引用操作;
	//void* p 不可以进行++--操作。
	return ((struct st*)e1)->age - ((struct st*)e2)->age;
	//负值:e1<e2;
	//0:e1=e2;
	//正值:e1>e2。
}
int cmp_string(const void* e1, const void* e2)
{
    
    
	//void* 可以接收任意类型的地址;
	//void* 不可以进行解引用操作;
	//void* p 不可以进行++--操作。
	return strcmp(((struct st*)e1)->arr , ((struct st*)e2)->arr);
	// strcmp(A,B)字符串比较函数,需要引用#include<string.h>
	//负值:e1<e2;
	//0:e1=e2;
	//正值:e1>e2。
}
void test3()//qsort()整型数组的用法。
{
    
    
	struct st s[3] = {
    
     {
    
    "zhangsan",4},{
    
    "lisi",5},{
    
    "wangwu",6} };
	int sz = sizeof(s) / sizeof(s[0]);
	qsort(s, sz, sizeof(s[0]), cmp_struct);
	for (int i = 0; i < sz; i++)
	{
    
    
		printf("%s ", s[i].arr);
	}
	printf("\n");
	qsort(s, sz, sizeof(s[0]), cmp_string);
	for (int i = 0; i < sz; i++)
	{
    
    
		printf("%s ", s[i].arr);
	}
}

运行结果

运行结果如下:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_45275802/article/details/112968004