Detailed explanation of C language library function qsort()

1. Function parameters

As you can see, this function parameter mainly has four parts

(1) void*base, this is the address of the first element of the array/string/structure to be sorted.

(2) size_t num is the number of sorted elements, the unit is byte, size_t is unsigned int type.

(3) size_t width is the size of each element sorted, in bytes.

(4) The last parameter is the address of a comparison function. This comparison function can be understood as a comparison method. qsort compares the relationship between each element by calling this method. That is to say, before we use qsort, we have to write a comparison function ourselves and use it as a template for qsort.

(5) This function needs to call the header file <stdlib.h>

2. The specific implementation of different data types (ascending order as an example)

1. Shaping int

Because the types of the functions connected to e1 and e2 are both void*, the type must be cast first.

To achieve descending order, it can be achieved by reversing e1 and e2 when returning.

int intcmp(const void* e1, const void* e2)
{
	return *(int*)e1 - *(int*)e2;
}

int main()
{
	int arr[6] = { 1,9,8,5,4,3 };
	qsort(arr, sizeof(arr) / sizeof(arr[0]), sizeof(arr[0]), intcmp);
}

2. Character char

int charcmp(const void* e1, const void* e2)
{
	return *(char*)e1 - *(char*)e2;
}

int main()
{
	char str[6] = {'a','s','d','f','g','c'};
	qsort(str, sizeof(str) / sizeof(str[0]), sizeof(str[0]), charcmp);
	return 0;
}

3. String char str[]

int charcmp(const void* e1, const void* e2)
{
	return *(char*)e1 - *(char*)e2;
}

int main()
{
	char str[6] = "adsbw";
	qsort(str, (sizeof(str) / sizeof(str[0])-1), sizeof(str[0]), charcmp);
	return 0;
}

4. Floating point type double&float

int doublecmp(const void* e1, const void* e2)
{
	return (int)(*(double*)e1 - *(double*)e2);
}

int main()
{
	double arr[6] = { 1.1,0.8,3.14,2.1,0.4,1.7 };
	qsort(arr, sizeof(arr) / sizeof(arr[0]), sizeof(arr[0]), doublecmp);
	return 0;
}

5. Structure

Can be compared based on each member of the structure.

typedef struct Stu
{
	char name[20];
	int age;
}stu;

int cmp_stu_age(const void* e1, const void* e2)
{
	return ((stu*)e1)->age - ((stu*)e2)->age;
}

int main()
{
	stu s[3] = { {"huangxiaoshun",20},{"zhangsan",29},{"lisi",17} };
	qsort(s, sizeof(s) / sizeof(s[0]), sizeof(s[0]), cmp_stu_age);
	return 0;
}

3. Summary

The key of qsort lies in the construction of the comparison function. Pay attention to the type of the function to be compared. The elements to be sorted are highly flexible, and the basis for sorting can be freely selected. To achieve descending order, you only need to swap the positions of e1 and e2 in the above code.

Guess you like

Origin blog.csdn.net/weixin_62244902/article/details/122205206