qsort() Sort an array with a comparison function

qsort() Sort an array with a comparison function

qsort() sorts an array in place using a consistent, transitive comparator. Stability is not guaranteed; avoid comparator subtraction, which may overflow.

Categorystdlib.h utilities
KindLibrary function
Header<stdlib.h>
C standardC89 / C90

📝 Syntax

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

⚙️ Parameters

base RequiredA pointer to the first element of the array to sort.
nmemb RequiredThe number of elements in the array.
size RequiredThe size of each element in bytes.
compar RequiredCompares two elements and returns negative, zero, or positive when the first is less than, equal to, or greater than the second.

Returns: No value is returned.

▶ Example

Edit the C code below and click Run; the server compiles and executes it:

Output:

7 7 19 42 88
⚠️ Warning The comparator must define a consistent, transitive ordering. Avoid return *(int *)a - *(int *)b because the subtraction can overflow.
💡 Tip Use sizeof array[0] for size and the element count for nmemb. Inside the comparator, convert each pointer to the correct element type.

📚 Related Tutorials

❓ FAQ

QWhy shouldn't a qsort comparator simply subtract the two integers?
ASubtracting extreme values can overflow signed int, causing undefined behavior and invalid ordering. Compare the values and return -1, 0, or 1 instead.
QIs qsort a stable sort?
AThe C standard does not guarantee stability, so equivalent elements need not retain their original order. Include an original index in the ordering or implement stability yourself if needed.
QWhy does a qsort comparator receive char ** when sorting an array of strings?
Aqsort passes the comparator a pointer to an array element. If each element is a char *, the element address is a char **. The comparator should convert it to const char *const *, dereference it to obtain the string pointer, and pass that pointer to strcmp; it must not treat the element address itself as the start of a string.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

Content reviewed by MOTO · Found an error? Report it

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏