Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C Library Function - qsort()

C Library Function - qsort()

C Standard Library - <stdlib.h> C Standard Library -

Description

qsort is a function provided by the C standard library used to perform a quicksort on an array. It is defined in header file.qsort It uses the quicksort algorithm, which is an efficient sorting algorithm with an average time complexity of O(n log n).

C Library Function **void qsort(void *base, size_t nitems, size_t size, int (*compar)(const void , const void)) ** sorts an array.

Declaration

The following is the declaration of the qsort() function.



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

Parameters

- Less than zero: indicates the first element is less than the second. - Equal to zero: indicates the two elements are equal. - Greater than zero: indicates the first element is greater than the second.

Return Value

This function does not return any value.

Example

The following example demonstrates the use of the qsort() function.

Example

#include

#include

// Define an array containing five integers

int

values

[

]

=

{

88

,

56

,

100

,

2

,

25

}

;

// Comparison function, used to compare two integers

int

cmpfunc

(

const

void

a

,

const

void

b

)

{

   

return

(

(

int

)

a

(

int

)

b

)

;

}

int

main

(

)

{

   

int

n

;

   

// Output the array contents before sorting

   

printf

(

"list before sorting:\n"

)

;

   

for

(

n

=

0

;

n

<

5

;

n

++

)

{

     

printf

(

"%d "

,

values

[

n

]

)

;

   

}

   

// Use the qsort function to sort the array

   

qsort

(

values

,

5

,

sizeof

(

int

)

,

cmpfunc

)

;

   

// Output the array contents after sorting

   

printf

(

"\nlist after sorting:\n"

)

;

   

for

(

n

=

0

;

n

<

5

;

n

++

)

{

     

printf

(

"%d "

,

values

[

n

]

)

;

   

}

 

   

return

0

;

}

Let's compile and run the above program, which will produce the following result:



List before sorting:

88 56 100 2 25 

Sorted list:

2 25 56 88 100

C Standard Library - <stdlib.h> C Standard Library -