BSearch and QSort

xiaoxiao2021-03-06  37

Use BSearch and QSort in , the basic writing method of comparison functions

1. Determine the order relationship of the comparative object;

2, the comparison function always uses two const void * parameters;

3. Conversion of the parameters correctly to the pointer to the type element type when the function begins;

4, in the first parameter is greater than, equal to, 2, 0, -1, respectively, when less than the second;

5, pay attention to the way of use.

-------------------------------------------------- -

Example: Assume that is sorted is an integer array. Define comparison functions:

INT ICMP (const void * p, const void * q) {

Const Int * m = p, * n = q;

RETURN * m> * n? 1: (* m == * n? 0: -1);

}

use:

INT * P, A [] = {5, 6, 3, 28, 23, 34, 7, 9, 6, 14}, k = 7;

Int main () {

...

Qsort (A, SizeOf (a) / sizeof (int), sizeof (int), ICMP);

/ * In this way, the elements of array A have been arranged in the rising order * /

P = BSearch (& K, A, SIZEOF (A) / Sizeof (int), Sizeof (int), ICMP);

/ * Pointer P will point to the position of the element 7 in array A * /

...

}

转载请注明原文地址:https://www.9cbs.com/read-51180.html

New Post(0)