qsort()

Sort an array

Synopsis:

#include <stdlib.h>

void qsort( void* base,
            size_t num,
            size_t width,
            int (*compare) (
                const void*,
                const void* ) );

Since:

BlackBerry 10.0.0

Arguments:

base
A pointer to the array that you want to sort.
num
The number of elements in the array.
width
The size of each element, in bytes.
compare
A pointer to a function that compares two entries. It's called with two arguments that point to elements in the array. The comparison function must return an integer less than, equal to, or greater than zero if the first argument is less than, equal to, or greater than the second argument.

Library:

libc

Use the -l c option to qcc to link against this library. This library is usually included automatically.

Description:

The qsort() function sorts the base array using the comparison function specified by compare. The array must have at least num elements, each of width bytes.

Examples:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char* some_strs[] = { "last", "middle", "first" };

int compare( const void* op1, const void* op2 )
{
    const char **p1 = (const char **) op1;
    const char **p2 = (const char **) op2;

    return( strcmp( *p1, *p2 ) );
}

int main( void )
{
    qsort( some_strs,
           sizeof( some_strs ) / sizeof( char * ),
           sizeof(char *),
           compare );

    printf( "%s %s %s\n",
        some_strs[0], some_strs[1], some_strs[2] );
        
    return EXIT_SUCCESS;
}

produces the output:

first last middle

Classification:

ANSI, POSIX 1003.1

Safety:  
Cancellation point No
Interrupt handler No
Signal handler No
Thread Yes

Last modified: 2014-06-24



Got questions about leaving a comment? Get answers from our Disqus FAQ.

comments powered by Disqus