原地址
function
<cstdlib>
qsort
void qsort (void* base, size_t num, size_t size, int (*compar)(const void*,const void*));
Sort elements of array
Sorts the
num elements of the array pointed to by
base, each element
size bytes long, using the
compar function to determine the order.
对由指针base指向的array数组的num个元素排序,每个元素的大小是size byte使用compar函数来决定顺序。
compar
This function is called repeatedly by qsort to compare two elements. It shall follow the following prototype:
| |
Taking two pointers as arguments (both converted to const void*). The function defines the order of the elements by returning (in a stable and transitive manner):
return value | meaning |
---|---|
<0 | The element pointed to by p1 goes before the element pointed to by p2 |
0 | The element pointed to by p1 is equivalent to the element pointed to by p2 |
>0 | The element pointed to by p1 goes after the element pointed to by p2 |
For types that can be compared using regular relational operators, a general compar function may look like:
| |
总结:
qsort第一个参数是指向基地址的指针,第二个参数是要排序的元素的个数,第三个参数是被排序的每个元素的大小,第四个参数是cmp函数,这个函数用来决定排序的顺序
关于cmp函数:由上面的例子可知,如果返回值大于0,a会被移到b的后面。如果小于0,a在b前。可以理解成默认是按降序。具体写法要参照具体情况。
一个例子:(整数数组arr按照升序排列)
int compareMyType (const void * a, const void * b)
{
if ( *(int*)a > *(int*)b ) return -1;
if ( *(int*)a == *(int*)b ) return 0;
if ( *(int*)a < *(int*)b ) return 1;
}