Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What sorting algorithm does qsort use?

Tags:

c

sorting

I can't find any information regarding what sorting algorithm C qsort function uses.

Is it quicksort? It is not mentioned in man.

like image 349
good_evening Avatar asked Nov 13 '12 00:11

good_evening


People also ask

What type of sort is qsort?

The qsort function implements a quick-sort algorithm to sort an array of number elements, each of width bytes. The argument base is a pointer to the base of the array to be sorted.

Is qsort quick sort?

No, they aren't. qsort() is a C standard library function. "Quicksort", on the other hand, is a specific sorting algorithm.

Does qsort sort in ascending order?

qsort() — Sort ArrayThe sorted array elements are stored in ascending order, as defined by your compare function. You can sort in reverse order by reversing the sense of “greater than” and “less than” in compare. The order of the elements is unspecified when two elements compare equally.

Which sorting algorithm is typically the algorithm implemented in the Unix qsort function?

Quicksort is widely used, and is typically the algorithm implemented in a library sort routine such as the UNIX qsort function.


1 Answers

The implementation of qsort is not specified: an implementation may use any sorting algorithm. Interestingly, the sort does not need to be stable, and there is no complexity requirement.

The entire specification of qsort (C11 §7.22.5.2) is as follows:

The qsort function

Synopsis

#include <stdlib.h>
void qsort(void *base, size_t nmemb, size_t size,
     int (*compar)(const void *, const void *));

Description

The qsort function sorts an array of nmemb objects, the initial element of which is pointed to by base. The size of each object is specified by size.

The contents of the array are sorted into ascending order according to a comparison function pointed to by compar, which is called with two arguments that point to the objects being compared. The function shall return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

If two elements compare as equal, their order in the resulting sorted array is unspecified.

Returns

The qsort function returns no value.

like image 119
James McNellis Avatar answered Sep 23 '22 07:09

James McNellis