Home > Backend Development > C#.Net Tutorial > How to use the qsort function

How to use the qsort function

DDD
Release: 2023-12-07 13:52:55
Original
841 people have browsed it

The qsort function is a library function in C language, used to sort arrays. Although the qsort function is very general and can handle any type of array, the comparison function can become complex, especially when dealing with complex data structures.

How to use the qsort function

The qsort function is a library function in C language that is used to sort arrays. It is defined in the header file. The prototype of the qsort function is:

void qsort(void *base, size_t nitems, size_t size, int (*compar)(const void *, const void*));
Copy after login

Here is the parameter description of the qsort function:

  1. base: points to the first element of the array to be sorted Pointer to the object.

  2. nitems: The number of elements in the array.

  3. size: The size of each element is usually obtained using the sizeof operator.

  4. compar: A comparison function used to determine the order of two elements. This function should accept two pointers, pointing to the elements to be compared, and return a negative number if the first element is less than the second, 0 if they are equal, and a positive number if the first element is greater than the second.

This is an example of using the qsort function, which sorts an array of integers:

#include <stdio.h>  
#include <stdlib.h>  
  
// 比较函数,用于决定排序  
int compare(const void *a, const void *b) {  
    int int_a = *((int*) a);  
    int int_b = *((int*) b);  
  
    if (int_a == int_b) return 0;  
    else if (int_a < int_b) return -1;  
    else return 1;  
}  
  
int main() {  
    int i;  
    int numbers[] = {7, 3, 4, 1, -1, 23, 12, 43, -8, 5};  
    int size = sizeof(numbers) / sizeof(int);  
  
    // 对数组进行排序  
    qsort(numbers, size, sizeof(int), compare);  
  
    // 输出排序后的数组  
    for(i = 0; i < size; i++) {  
        printf("%d ", numbers[i]);  
    }  
  
    return 0;  
}
Copy after login

Note: Although the qsort function is very general and can handle any type of array , but its comparison functions can get complicated, especially when you're dealing with complex data structures. When writing a comparison function, make sure it works as you expect.

The above is the detailed content of How to use the qsort function. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template