[C Language] Take you to play with the library function qsort

insert image description here

Junxi_'s personal homepage

Be diligent and encourage the years to wait for no one

C/C++ game development


Hello, Mina-san, this is Junxi_. Previous updates have always been relatively basic and simple content. With the improvement of the blogger’s own level, today I will bring you something different. What we are going to talk about today is the usage of the library function qsort. Not much nonsense, let’s start directly
!

1. Basic introduction of qsort function

Bubble Sort

Many people may have heard of the qsort function for the first time, but it is actually a kind of bubble sort, but our previous bubble sort can only sort integers, while the qsort function can sort more other types of data

  • What is bubble sort?
  • Compare the elements of an unordered array from left to right. If the left element is larger than the right element, exchange the positions of the two elements, and continue to compare with the next right element until the unordered array is arranged into an array with elements from small to large (that is, an ascending array). So bubble sort is also called ascending sort method.
  • I have written a related blog before and introduced this content in detail, so I won’t repeat it here. If you are interested, please see the link below: [C Language
    Elementary] Take you to play with arrays in C language, and gradually realize bubble sorting, backgammon, minesweeping
  • This is not the key content here but it is related to the following content, so I will just post the code!
void bubble_sort(int arr[], int sz)//参数接收数组元素个数
{
    
    
	int i = 0;
		for (i = 0; i < sz - 1; i++)
		{
    
    
			int j = 0;
			for (j = 0; j < sz - i - 1; j++)
			{
    
    
				if (arr[j] > arr[j + 1])
				{
    
    
					int tmp = arr[j];
					arr[j] = arr[j + 1];
					arr[j + 1] = tmp;
				}
			}
		}
	
}
int main()
{
    
    
	int i;
	int arr[] = {
    
     3,1,7,5,8,9,0,2,4,6 };
	int sz = sizeof(arr) / sizeof(arr[0]);//直接把元素个数传进去
	bubble_sort(arr, sz);
	for (i = 0; i < sz; i++)
	{
    
    
		printf("%d ", arr[i]);
	}
	return 0;
}

  • operation result
    insert image description here

Two.qsort function

  • 为了系统的熟悉并了解qsort函数,这里我们先看看c plus plus中对这个函数的定义
    insert image description here
  • We can see from the definition of this function that four parameters need to be passed in when this function is called
  • void * base
    passes in the address of the array that needs to be sorted. The type of the array we pass in here is uncertain, and the void type is used uniformly here.
  • size_t num
    passes in the size of the array. If you want to sort an array, you must know how big the array is.
  • size_t size
    The byte size occupied by an element in the incoming array. Since different types of data occupy different types, you need to inform the size of the element in the qsort array when using it
  • int ( * compar )(const void * , const void )
    We can see that this is a function pointer, and the two parameters that this function pointer needs to pass in are both void
    types. This is more complicated, and we will expand it later.
  • In addition, as a library function, using the qsort function needs to refer to the header file, and the header file of qsort is
#include<stdlib.h>

1. Integer data is sorted using qsort

  • Now that we have the knowledge of bubble sorting, let's start with the simplest use of qsort for integer data, so that it is easy for everyone to understand
  • Not much to say, let's look at the code first
//整型
int compar(const void*p1, const void*p2)
{
    
    
    return (*(int*)p1 - *(int*)p2);
}
int main()
{
    
    
    int arr[10] = {
    
     1,4,6,8,3,8,9,2,0,10 };
    int sz = sizeof(arr) / sizeof(arr[0]);
    //test_1();
    qsort(arr, sz, sizeof(int),compar);
    int i = 0;
    for (i = 0; i < sz; i++)
    {
    
    
        printf("%d ", arr[i]);
    }
        return 0;
}
  • result
    insert image description here
  • It has fulfilled our requirement very well, let’s explain it now
  • First of all, let's look at the main function. We defined an integer array and put 10 integer data in random order. Then we calculated the size of the array and saved it in sz. Since we sorted integer data, we can calculate the size of bytes occupied by a data by sizeof (int)
  • Let's now talk about the last parameter in detail
int compar(const void*p1, const void*p2)
{
    
    
    return (*(int*)p1 - *(int*)p2);
}
  • 上面qsort定义中是一个函数指针,我们现在这里直接定义一个函数并把该函数的地址传入即可,如上代码
  • What is the use of this function? Let's put aside the whole and only focus on this function, and found thatIt casts the incoming two void type pointers to int type, and subtracts the data pointed to by the two pointers by dereferencing, then the results at this time are nothing more than three situations
  • p1>p2, return a number greater than 0
  • p1=p2, return 0
  • p1<p2, return a number less than 0
  • This is the step of comparing the size of two elements in our previous bubble sort. When using qsort, we don't need to implement the exchange, we just need to tell it which element is larger and which element is smaller. That is to say, in qsort
  • If a number greater than 0 is returned, the positions of the two are exchanged
  • Returns a number less than or equal to 0, unchanged
    注意:这里的p1指向前一个数,而p2指向后一个数,这样通过不断比较交换就可以实现我们的升序排序了
  • Prove what I said above
  • If the above logic is correct, if we want to achieve descending order, do we just need to change p1-p2 to p2-p1?
int compar(const void*p1, const void*p2)
{
    
    
    return (*(int*)p2 - *(int*)p1);
}

insert image description here

  • birdie so
    insert image description here

2. Use qsort to sort the custom structure

  • Other data types are exactly the same as integers. Now let’s talk about how to sort structure data through qsort

  • Note that if there are multiple types of data in the structure, since our qsort sorts the data in the array, the data passed in must be of the same type when used
    .

  • code show as below:

  • The first introduction is to sort by the age in the structure

//测试qsort排序结构体数据
struct Stu
{
    
    
	char name[20];
	int age;
};

int cmp_stu_by_age(const void* p1, const void* p2)
{
    
    
	return ((struct Stu*)p1)->age - ((struct Stu*)p2)->age;
}

void test2()
{
    
    
	struct Stu arr[] = {
    
     {
    
    "zhangsan", 20}, {
    
    "lisi", 50},{
    
    "wangwu", 15} };
	int sz = sizeof(arr) / sizeof(arr[0]); 
	qsort(arr, sz, sizeof(arr[0]), cmp_stu_by_age);
}
int main()
{
    
    
	test2();
	return 0;
}
  • We can see through monitoring that our structure array is now arranged in ascending order of age
    insert image description here
  • We first define a structure with two elements in it: name and age
  • Then we defined a structure array and initialized three elements into it
struct Stu arr[] = {
    
     {
    
    "zhangsan", 20}, {
    
    "lisi", 50},{
    
    "wangwu", 15} };
  • After that, we still calculate the size of the array, and calculate the bytes occupied by each element in the array by calculating the size of the first element
  • Finally, we can see that it is sorting by the second element in the structure, that is, the age
int cmp_stu_by_age(const void* p1, const void* p2)
{
    
    
	return ((struct Stu*)p1)->age - ((struct Stu*)p2)->age;
}

Here we compare the size by converting p1 and p2 into the type of structure pointer and pointing to the age element in the structure through the "->" operator

  • sort by size
  • Others are the same as above, this time we compare the size and sort by name
  • code show as below:
int cmp_stu_by_name(const void* p1, const void* p2)
{
    
    
	return strcmp(((struct Stu*)p1)->name, ((struct Stu*)p2)->name);
}

void test3()
{
    
    
	struct Stu arr[] = {
    
     {
    
    "zhangsan", 20}, {
    
    "lisi", 50},{
    
    "wangwu", 15} };
	int sz = sizeof(arr) / sizeof(arr[0]);
	qsort(arr, sz, sizeof(arr[0]), cmp_stu_by_name);
}
int main()
{
    
    
	test3();
	return 0;
}
  • We still look at the results through debugging
    insert image description here
  • The first element has become lisi, we can see that it is wangwu after age, and zhangsan can be seen that it has been sorted
  • Here we briefly introduce the rules for comparing the size of strings

String Comparison Size Rules

  • For comparing the size of two character strings, it is actually comparing the size of the ASCLL code value of the character at the corresponding position. If the ASCLL value at the same position is the same, compare the next position until there is a difference.
  • 比如上面这段代码的比较,在首元素上分别是'l','w','z',其中‘l’ASCLL码值最小,排在首位,'w'ASCLL码值居中,'z'ASCLL码值最大,排在最后,这就是出现上面结果的原因。

Summarize

  • This is the end of today's content, in which we introduced the use of the qsort function. Due to space constraints, the simulation implementation of the qsort function will be explained in the next blog. During this period, if you are still confused about the qsort function, you may wish to use it yourself.

  • Well, if you have any questions, please ask me in the comment area or private message, see you next time!

It is not easy for a new blogger to create. If you feel that the content of the article is helpful to you, you may wish to click on this new blogger before leaving. Your support is my motivation to update! ! !

**(Ke Li asks you to support the blogger three times in a row!!! Click the comment below to like and collect to help Ke Li)**

insert image description here

Guess you like

Origin blog.csdn.net/syf666250/article/details/131628259