Talking about the qsort function

void qsort (void* base, size_t num, size_t size,
            int (*compar)(const void*,const void*));

Sort Elements
of an Array Sorts the num elements of an array, each of size in bytes, using a comparison function to determine the order.

The sorting algorithm used by this function compares pairs of elements by taking the specified compar function with pointers to them as arguments.

This function returns no value, but modifies the contents of the array pointed to by basically reordering its elements according to the compar definition.

base is the starting address, num is the number of elements, size is the size of the element in bytes, compar is the function used for sorting, and the parameter is const void*.

define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
int com_int(const void* e1, const void* e2)
{
	return *(int*)e1 - *(int*)e2;
}
void test()
{
	int arr[] = { 5,6,9,8,2,1,7,3,0,4 };
	int sz = sizeof(arr) / sizeof(arr[0]);
	qsort(arr, sz, sizeof(arr[0]), com_int);
	for (int i = 0; i < sz; i++)
	{
		printf("%d", arr[i]);
	}
}
int main()
{
	test();
}

As in the above program, first write the comparison function com_int to set the sorting method, and the setting of the return value is obtained by subtracting the elements, so the sorting result is in ascending order.

Then set the array in the test function, call the qsort function, and print the result.

 

Guess you like

Origin blog.csdn.net/m0_63742310/article/details/123544718