Home  >  Article  >  Backend Development  >  The difference between C qsort() and C++ sort()

The difference between C qsort() and C++ sort()

WBOY
WBOYforward
2023-09-20 21:25:021273browse

C qsort()与C++ sort()的区别

Here, we will see the difference between qsort() in C language and sort() in C language.

C language provides the qsort() function, which can be used to sort arrays. The parameters and syntax of the function are shown below.

void qsort(void *base, size_t num, size_t size, int (*comparator) (const void*, const void*));

This function accepts the base address of the array, the number of elements in the array, the size of each item in the array, and a comparison function.

C provides the sort() function, which is located in the C STL. Its parameters and syntax are shown below.

void sort(T first, T last, Compare c);

There is no guarantee that the order of repeated elements is preserved. To achieve this, we can use stable_sort provided by C STL.

The difference between qsort() and sort()

qsort() in C sort() in C
#It uses quick sort algorithm. It uses introsort. This is a hybrid sorting algorithm. Different implementations use different algorithms. GNU C STL uses a three-part hybrid sort. Introsort, Quicksort and Insertion Sort.
The C standard does not mention this issue.
The complexity of this sorting algorithm. In this case, the complexity of C 11's sort() function is O(n logn). Some previous versions of the sort() function had a worst-case complexity of O(n2), while in the average case their complexity was O(nlogn). The running time of this sort is compared to sort() The running time is less than qsort(). qsort() is not flexible enough for different types. sort() The running time is less than qsort(). qsort() is not flexible enough for different types sort() is flexible. It can sort C arrays, C vectors, C deques, and some other containers. This sorting method is not type-safe. It uses unsafe void pointers to access data. This sorting technique is safer. It does not require the use of any unsafe void pointers to access data.

The above is the detailed content of The difference between C qsort() and C++ sort(). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete