C language - the use of qsort function (detailed explanation)

Foreword:

The qsort() function (quick sort) is a quick sort among the eight sorting algorithms, which can sort arrays of any data type, including integers, floating point types, strings, and even custom structure types.

1. The meaning of the qsort function

Click on the website: https://cplusplus.com/reference/ ——> click to view the old version of the function hyperlink interface (to view the meaning of the function) the
old version
insert image description here
Enter the function you want to query in the search box
insert image description here
to view the meaning of the qsort function
insert image description here
Translation:
insert image description here

1.1 Function parameters

//void qsort(void* base,//指向了需要排序的数组的第一个元素
// siez_t num, //排序的元素个数
// size_t size, //一个元素类型的大小,单位是字节。
// int (*compar)(const void*, const void*))//函数指针类型——这个函数指针指向的函数能够比较base指向数组中的两个元素。

The function has four parameters: the first parameter is a pointer; size_t is an unsigned integer (the second and third parameters); the fourth parameter is a function pointer type.
Sort the num elements pointed to by base, each element has a length of size bytes, use the function pointed to by this comper to detect the order (comparison order)

1.2 Meaning of parameters

base: base points to the first element of the array to be sorted and is converted to void*.
num: The number of elements in the array space pointed to by base, which is an unsigned integer.
size: The unit of each element is the number of bytes, it is an unsigned integer.
comper: Pointer to a function that compares two elements
int comper (const void* p1, const void* p2);
compares two functions, the value pointed to by p1 is compared with the value pointed to by p2:
the value pointed to by p1 is greater than the value pointed to by p2 , returns a number >0;
if the value pointed to by p1 is equal to the value pointed to by p2, then returns a number equal to 0; if the
value pointed to by p1 is smaller than the value pointed to by p2, returns a number <0;

2. Test sqort with different types of data

2.1 Sort the integers in the array

Ascending order of integers:

#include <stdio.h>
#include <stdlib.h>
int comper(const void* p1, const void* p2)
{
    
    
    return (*(int*)p1 - *(int*)p2);
}
int main()
{
    
    
    int arr1[10] = {
    
     3,6,8,2,6,9,1,5,8,4 };
    qsort(arr1,sizeof(arr1)/sizeof(arr1[0]),sizeof(int),comper);
    int i = 0;
    for (i = 0; i < sizeof(arr1) / sizeof(arr1[0]); i++)
        printf("%d ", arr1[i]);
    return 0;
}

2.2 Sort the floating point numbers in the array

#include <stdio.h>
#include <stdlib.h>
int comper(const void* p1, const void* p2)
{
    
    
    return (*(float*)p1 - *(float*)p2);
}
int main()
{
    
    
    float arr1[10] = {
    
     3.33,6.66,8.88,2.22,6.66,9.99,1.11,5.55,8.88,4.44 };
    qsort(arr1, sizeof(arr1) / sizeof(arr1[0]), sizeof(float), comper);
    int i = 0;
    for (i = 0; i < sizeof(arr1) / sizeof(arr1[0]); i++)
        printf("%0.3f ", arr1[i]);
    return 0;
}

2.3 Sorting strings

#include <stdio.h>
#include <stdlib.h>
int comper(const void* p1, const void* p2)
{
    
    
    return (*(char*)p1 - *(char*)p2);
}
int main()
{
    
    
    char arr1[10] = "asdfghjkl";
    qsort(arr1, sizeof(arr1) / sizeof(arr1[0]), sizeof(char), comper);
    int i = 0;
    for (i = 0; i < sizeof(arr1) / sizeof(arr1[0]); i++)
        printf("%c ", arr1[i]);
    return 0;
}

2.4 Sorting the structure

The structure is sorted by character size


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct str
{
    
    
    char arr[10];
    int age;
};
int comper(const void* p1, const void* p2)
{
    
    
    return strcmp(((struct str*)p1)->arr,((struct str*)p2)->arr);
}
int main()
{
    
    

    struct str ar[3] = {
    
    {
    
    "pan",19},{
    
    "wang",21},{
    
    "li",31}};
    qsort(ar, sizeof(ar) / sizeof(ar[0]), sizeof(ar[0]), comper);
    int i = 0;
    for (i = 0; i < sizeof(ar) / sizeof(ar[0]); i++)
        printf("%s,%d\n", ar[i].arr, ar[i].age);
    return 0;
}

3. Simulate the implementation of qsort function

  1. The idea of ​​using bubble sort
  2. Applicable to any type of data sorting
    Problem 1: Parameters can only accept integer arrays
    Solution 1: pointer to void*
//void qsort(void* base,//指向了需要排序的数组的第一个元素
// siez_t num, //排序的元素个数
// size_t size, //一个元素类型的大小,单位是字节。
// int (*compar)(const void*, const void*))//函数指针类型——这个函数指针指向的函数能够比较base指向数组中的两个元素。

Question 2: Integer comparison size < > ==
structure comparison size, you need to see the member type for comparison.
For different types of data, you cannot simply use > to compare.
Solution 2: Pass the comparison method of two elements as a function parameter.

int comp(const void* p1, const void* p2)
{
    
    
    return (*(int*)p1 - *(int*)p2);
}

Overall implementation:

//模拟实现qsort函数
#include <stdio.h>
int comp(const void* p1, const void* p2)
{
    
    
    return (*(int*)p1 - *(int*)p2);
}
void swap(void* p1, void* p2,int si)//元素arr[j]和元素arr[j+1]进行交换,si表示交换的字节大小
{
    
    
    int i = 0;
    for (i = 0; i < si; i++)//把每个字节进行交换,整体就进行交换了
    {
    
    
        char tmp = *((char*)p1 +  i);
        *((char*)p1 + i) = *((char*)p2 + i);
        *((char*)p2 + i) =tmp ;
    }
}
void qsort(char* base, int num, int si, int(*com)(const void* ,const void*))//
{
    
    
    int i, j;
    for(i=0;i<num-1;i++)
        for (j = 0; j < num - i - 1; j++)
        {
    
    
            if (com((char*)base + si * j, (char*)base + (j + 1) * si) > 0)//由小到大排序,两元素比较大小,将arr[j]和arr[j+1]的地址传递给com函数
            {
    
    
                swap((char*)base + si * j, (char*)base + (j + 1) * si,si);//进行交换
            }
        }
}
int main()
{
    
    
    int arr[15] = {
    
     1,3,5,7,9,11,13,15,14,12,10,8,6,4,2 };//定义一个整型数组
    int zs = sizeof(arr) / sizeof(arr[0]);
    qsort(arr, zs, sizeof(int), comp);
    int i;
    for (i = 0; i < zs; i++)
        printf("%d ", arr[i]);
    return 0;
}

insert image description here

Guess you like

Origin blog.csdn.net/plj521/article/details/131819291